package com.imooc.IOStreamReaderWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; public class IsrAndOswDemo { public static void main(String[] args) throws IOException { FileInputStream in = new FileInputStream( "H:\\Users\\MeRos\\Workspaces\\Projects\\测试文本文件(utf-8)\\src\\测试文件(utf-8).txt"); InputStreamReader isr = new InputStreamReader(in); // 默认的项目编码 FileOutputStream out = new FileOutputStream("字符流文本.txt"); OutputStreamWriter osw = new OutputStreamWriter(out,"gbk"); /* * int c ; while((c = isr.read()) != -1){ System.out.print((char) c); } */ char[] buffer = new char[8 * 1024]; int c; // 批量读取,放入buffer字符数组,从第0个位置开始,最多放buffer.length个 // 返回的是读到的字符的个数 while ((c = isr.read(buffer, 0, buffer.length)) != -1) { String s = new String(buffer, 0, c); System.out.print(s); } in.close(); out.close(); isr.close(); osw.close(); } }
我的文件是utf-8 的(存在新建的项目中也是utf-8),测试项目是gbk的,可是输出控制台之后怎么不会发生乱码呢.????
因为你while循环里将字符数组转换为String类型时,会自动添上项目默认编码(你的是utf-8),只要文本文件的编码和你输入流的编码一样,控制台应该就会正确输出吧