本笔记来源于:尚硅谷Java零基础全套视频教程(宋红康2023版,java入门自学必备)
b站视频
1.转换流涉及到的类:属于字符流
InputStreamReader:将一个字节的输入流转换为字符的输入流
解码:字节、字节数组 —>字符数组、字符串
OutputStreamWriter:将一个字符的输出流转换为字节的输出流
编码:字符数组、字符串 —> 字节、字节数组
说明:编码决定了解码的方式
2.作用:提供字节流与字符流之间的转换
3.图示:

4.典型实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| @Test public void test1() throws IOException {
FileInputStream fis = new FileInputStream("dbcp.txt"); InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
char[] cbuf = new char[20]; int len; while((len = isr.read(cbuf)) != -1){ String str = new String(cbuf,0,len); System.out.print(str); }
isr.close();
}
|
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
|
@Test public void test2() throws Exception { File file1 = new File("dbcp.txt"); File file2 = new File("dbcp_gbk.txt");
FileInputStream fis = new FileInputStream(file1); FileOutputStream fos = new FileOutputStream(file2);
InputStreamReader isr = new InputStreamReader(fis,"utf-8"); OutputStreamWriter osw = new OutputStreamWriter(fos,"gbk");
char[] cbuf = new char[20]; int len; while((len = isr.read(cbuf)) != -1){ osw.write(cbuf,0,len); }
isr.close(); osw.close(); }
|
5.说明:
//文件编码的方式(比如:GBK),决定了解析时使用的字符集(也只能是GBK)。