演示使用InputStreamReader和OutputStreamWriter
- InputStreamReader
package com.io.reader; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; /** * 演示使用InputStreamReader转换流解决中文乱码问题 * 将字节流FileInputStream转成字符流InputStreamReader,指定编码gbk/utf-8 */ public class InputStreamReader_ { public static void main(String[] args) throws Exception{ String filePath = "d:\\a.txt";//注文件中的a.txt保存的类型是ANSI,所以编码方式要选gbk //1.把FileInputStream转成 InputStreamReader //2.指定编码为gbk InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "gbk"); //3.把 InputStreamReader传入BufferedReader BufferedReader br = new BufferedReader(isr); //4.读取 String s= br.readLine(); System.out.println("读取内容="+s); //5.关闭外层流,底层流FileInputStream会自动关闭 br.close(); } }
- OutputStreamWriter
package com.io.writer; import java.io.*; /** * 演示使用OutputStreamWriter * 将字节流FileOutputStream转成字符流OutputStreamWriter,指定编码gbk/utf-8 */ public class OutputStreamWriter_ { public static void main(String[] args) throws IOException { String filePath="d:\\cyy.txt"; String charSet="gbk"; OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath),charSet); osw.write("hi,沐晴"); osw.close(); System.out.println("按照"+charSet+"保存文件成功"); } }