转换流:处理流的一种
转换流提供了在字节流和字符流之间的转换
- Java API提供了两个转换流:(属于字符流)
-
- InputStreamReader:将InputStream转换为Reader
-
- OutputStreamWriter:将Writer转换为OutputStream
- 字节流中的数据都是字符时,转成字符流操作更高效。
- 很多时候我们使用转换流来处理文件乱码问题。实现编码和解码的功能。
InputStreamReader
OutputStreamWriter
//读入utf-8编码的文件,并以gbk编码的格式输出
package com.senior.iostream;
import java.io.*;
/**
* @author eden
* @Description
* @create projectTest-com.senior.iostream:2021-05-13-20:41
* @since
*/
public class TransStream {
public static void main(String[] args) {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
InputStreamReader inputStreamReader = null;
OutputStreamWriter outputStreamWriter =null;
try {
File file = new File("JavaSenior\\data.txt");
File file1 = new File("JavaSenior\\data_gbk.txt");
fileInputStream = new FileInputStream(file);//通过字节流的形式读入
fileOutputStream = new FileOutputStream(file1,true);//输出流输出
//参数2指明了字符集,具体使用什么字符集,取决于文件保存时使用的字符集
//按照指定字符集,把读入的字节流转换为字符流
inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
//以gbk字符集的格式输出的输出文件中
outputStreamWriter = new OutputStreamWriter(fileOutputStream,"gbk");
char[] ch = new char[5];
int len;
while ((len = inputStreamReader.read(ch)) != -1) {
String str = new String(ch, 0, len);
outputStreamWriter.write(str);
System.out.print(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inputStreamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStreamWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
该博客图片来源于尚硅谷宋老师教学课件