视频链接:16.24 转换流的使用_哔哩哔哩_bilibilihttps://www.bilibili.com/video/BV1Tz4y1X7H7?spm_id_from=333.788.videopod.episodes&vd_source=b5775c3a4ea16a5306db9c7c1c1486b5&p=24
1.InputStreamReader使用
package com.yundait.Demo05;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
public class InputStreamReaderDemo01 {
public static void main(String[] args) throws Exception {
//1创建InputStreamReader
FileInputStream fis = new FileInputStream("C:\\Users\\Public\\Documents\\ggg1.txt");
InputStreamReader isr = new InputStreamReader(fis, "gbk");//可以选择读取文件时使用的字符编码标准
//2读取文件
int data;
while ((data = isr.read())!=-1){
System.out.print((char) data);
}
//3关闭
isr.close();
}
}
2.OutputStreamWriter使用
package com.yundait.Demo05;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
public class OutputStreamWriterDemo01 {
public static void main(String[] args) throws Exception {
//创建转换流
FileOutputStream fos = new FileOutputStream("C:\\Users\\Public\\Documents\\ggg1.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos, "gbk");
//写入文件
for(int i=0; i<10; i++){
osw.write("好好学习,天天向上\r\n");
osw.flush();
}
//3关闭
osw.close();
System.out.println("执行完毕");
}
}