JavaIO流之转换流
转换流
字符流中和编码解码问题相关的两个类

-
InputStreamReader:是从字节流到字符流的桥梁,父类是Reader
它读取字节,并使用指定的编码将其解码为字符
它使用的字符集可以由名称指定,也可以被明确指定,或者可以接受平台的默认字符集
-
OutputStreamWriter:是从字符流到字节流的桥梁,父类是Writer
是从字符流到字节流的桥梁,使用指定的编码将写入的字符编码为字节
它使用的字符集可以由名称指定,也可以被明确指定,或者可以接受平台的默认字符集

使用Ctrl + B查看源码,查看FileReader字符流
FileReader fr = new FileReader("myCharStream\\b.txt");
其中FileInputStream就是字节流
public FileReader(String fileName) throws FileNotFoundException {
super(new FileInputStream(fileName));
}
FileReader的父类就是InputStreamReader,字符输入流就是通过转换流,把字节流进行了一个转换,再读取数据。

转换流读写数据
构造方法
| 方法名 | 说明 |
|---|---|
| InputStreamReader(InputStream in) | 使用默认字符编码创建InputStreamReader对象 |
| InputStreamReader(InputStream in,String chatset) | 使用指定的字符编码创建InputStreamReader对象 |
| OutputStreamWriter(OutputStream out) | 使用默认字符编码创建OutputStreamWriter对象 |
| OutputStreamWriter(OutputStream out,String charset) | 使用指定的字符编码创建OutputStreamWriter对象 |
Coding
public class OutputDemo06 {
public static void main(String[] args) throws IOException, IOException {
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("osw.txt"),"GBK");
osw.write("中国");
osw.close();
InputStreamReader isr = new InputStreamReader(new FileInputStream("osw.txt"),"GBK");
int ch;
while ((ch=isr.read())!=-1) {
System.out.print((char)ch);
}
isr.close();
}
}
注:在JDK11之前,转换流可以指定编码读写,而在JDK11之后,FileReader类中

新增了一个构造方法如上所示。
可以在FileReader的参数中指定编码的格式。
FileReader fr = new FileReader("ow.txt", Charset.forName("gbk"));
总的来说,在JDK11之后就不用使用转换流了,字符流里面底层集成了转换流的功能。

浙公网安备 33010602011771号