3-转换流

image-20221223002648360

InputStreamReader 的构造方法为传入一个 inputStream(字节输入流), 和指定编码(charsetDecoder)

Reader的包装类 BufferedReader 的构造器接受对象为 Reader 的子类,inputStreamReader 也属于,可以直接进行包装

步骤

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//如果有特定编码,不是utf-8,则需要进行转换
BufferedReader bufferedReader=null;
try {
//1.先创建字节节点流
//2.将字节流转换为字符流 使用inputStreamReader
//3.包装
FileInputStream fileInputStream = new FileInputStream("e:\\mytemp\\hw2.txt");
InputStreamReader gbk = new InputStreamReader(fileInputStream, "gbk");
bufferedReader = new BufferedReader(gbk);
String line="";
int cout=1;
while ((line=bufferedReader.readLine())!=null){
System.out.println("第"+cout+"内容"+line);
cout++;
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} finally {
if (bufferedReader!=null){
bufferedReader.close();
}
}