处理流之二:转换流

转换流提供了在字节流和字符流之间的转换

Java API提供了两个转换流:

  • InputStreamReader:将InputStream转换为Reader 字节输入流->字符输出流
  • OutputStreamWriter:将Writer转换为OutputStream 字符输入流->字节输出流

字节流中的数据都是字符时,转成字符流操作更高效。

很多时候我们使用转换流来处理文件乱码问题。实现编码和解码的功能。

解码:字节、字节数组 —>字符数组、字符串

编码:字符数组、字符串 —> 字节、字节数组

1

InputStreamReader和OutputStreamWriter

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)

image-20200516163905208

image-20200516163930253

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.*;

/**
* .转换流:属于字符流
* InputStreamReader:将一个字节的输入流转换为字符的输入流
* OutputStreamWriter:将一个字符的输出流转换为字节的输出流
* <p>
* 2.作用:提供字节流与字符流之间的转换
* <p>
* 3. 解码:字节、字节数组 --->字符数组、字符串
* 编码:字符数组、字符串 ---> 字节、字节数组
* <p>
* <p>
* 4.字符集
* ASCII:美国标准信息交换码。
* 用一个字节的7位可以表示。
* ISO8859-1:拉丁码表。欧洲码表
* 用一个字节的8位表示。
* GB2312:中国的中文编码表。最多两个字节编码所有字符
* GBK:中国的中文编码表升级,融合了更多的中文文字符号。最多两个字节编码
* Unicode:国际标准码,融合了目前人类使用的所有字符。为每个字符分配唯一的字符码。所有的文字都用两个字节来表示。
* UTF-8:变长的编码方式,可用1-4个字节来表示一个字符。
*/
public class InputStreamReaderTest {

@Test
public void test1() {

InputStreamReader isr = null;
try {
FileInputStream fis = new FileInputStream("dbcp.txt");
// InputStreamReader isr = new InputStreamReader(fis);//使用系统默认的字符集
//参数2指明了字符集,具体使用哪个字符集,取绝于文件保存时所使用的字符集。
isr = new InputStreamReader(fis, "UTF-8");

char[] cbuf = new char[20];
int len;
while ((len = isr.read(cbuf)) != -1) {
/*for (int i = 0; i < len; i++) {
char c = cbuf[i];
System.out.print(c);
}*/
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();
}
}
}
}

//综合使用InputStreamReader和OutputStreamWriter
@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();
}
}
}
}
}