`

IO流读文件 中文乱码

阅读更多

一段很简单读文件代码

 

public class TestFileReader {
    public static void main(String[] args) {
        FileReader fr=null;
        BufferedReader br=null;
        try {
            fr=new FileReader("D:/ncolog1.txt");
            br=new BufferedReader(fr);
            String read=null;
            while((read=br.readLine())!=null){
                System.out.println(read);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            try {
                if(fr!=null){
                    fr.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

 在一台机器上测试输出正常数据,另外一台机器中文乱码。

 

查看JVM 文件编码参数

String encoding = System.getProperty("file.encoding");

 输出正常机器上显示为GBK,中文乱码机器上显示为UTF-8.

用EditPlus查看ncolog1.txt编码为ANSI.

 

百度ANSI编码的信息

这些使用 2 个字节来代表一个字符的各种汉字延伸编码方式,称为 ANSI 编码。
在简体中文系统下,ANSI 编码代表 GB2312 编码。

 

解决方法

1. 运行时,加虚拟机参数 -Dfile.encoding=GBK

2.

InputStreamReader read = new InputStreamReader(new FileInputStream("D:/ncolog1.txt"),"GBK");
BufferedReader reader=new BufferedReader(read); 

 

 

 

附:

关于ansi编码的BUG
  很多细心的人会发现,当新建文本文档只输入“联通”2字保存再打开时将是乱码。
  当txt文档中一切字符都在 C0≤AA≤DF 80≤BB≤BF 这个范围时,notepad都无法确认文档地格式,没有自动依照UTF-8格式来"Display"。 而"联通"就是C1 AA CD A8,刚好在上面地范围内,所以不能正常显现。
  记事本默认是以ANSI编码保存文本文档的,而正是这种编码存在的bug招致了上述怪现象。假如保存时选择Unicode、Unicode(big endian)、UTF-8编码就正常了。此外,假如以ANSI编码保存含有某些特别符号的文本文档,再次打开后符号也会变成英文问号。例如输入英文 this app can break 以ANSI编码保存也会变成乱码
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics