处理流之二:转换流
转换流提供了在字节流和字符流之间的转换
Java API提供了两个转换流:
- InputStreamReader:将InputStream转换为Reader 字节输入流->字符输出流
- OutputStreamWriter:将Writer转换为OutputStream 字符输入流->字节输出流
字节流中的数据都是字符时,转成字符流操作更高效。
很多时候我们使用转换流来处理文件乱码问题。实现编码和解码的功能。
解码:字节、字节数组 —>字符数组、字符串
编码:字符数组、字符串 —> 字节、字节数组

InputStreamReader
实现将字节的输入流按指定字符集转换为字符的输入流。 需要和InputStream“套接”。
常用构造器
1
| public InputStreamReader(InputStream in)
|
1
| public InputSreamReader(InputStream in,String charsetName)
|
如: Reader isr = new InputStreamReader(System.in,”gbk”);指定字符集
OutputStreamWriter
实现将字符的输出流按指定字符集转换为字节的输出流。需要和OutputStream“套接”。
构造器
1
| public OutputStreamWriter(OutputStream out)
|
1
| public OutputSreamWriter(OutputStream out,String charsetName)
|



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| import org.junit.Test;
import java.io.*;
public class InputStreamReaderTest {
@Test public void test1() {
InputStreamReader isr = null; try { FileInputStream fis = new FileInputStream("dbcp.txt");
isr = new InputStreamReader(fis, "UTF-8");
char[] cbuf = new char[20]; int len; while ((len = isr.read(cbuf)) != -1) {
String s = new String(cbuf, 0, len); System.out.print(s); } } catch (IOException e) { e.printStackTrace(); } finally { if (isr != null) { try { isr.close(); } catch (IOException e) { e.printStackTrace(); } } } }
@Test public void test2() { InputStreamReader isr = null; OutputStreamWriter osw = null; try { isr = new InputStreamReader(new FileInputStream("dbcp.txt"), "utf-8"); osw = new OutputStreamWriter(new FileOutputStream("dbcp-gbk.txt"), "gbk");
char[] cbuf = new char[20]; int len; while ((len = isr.read(cbuf)) != -1) { osw.write(cbuf, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { if (isr != null) { try { isr.close(); } catch (IOException e) { e.printStackTrace(); } } if (osw != null) { try { osw.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
|