jvm 默认字符集

最近在读取第三方上传的文件时,遇到一个问题,就是采用默认字符集读取,发现个别中文乱码,找到乱码的字,发现是生僻字:碶。

由于在window是环境下做的测试,并没有报错,但是在linux服务器上执行,发现读出后是乱码。

具体读取文件代码简化如下:

 Path path = Paths.get("d:", "1.txt");
 String ss = null;
 try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path.toString()))) {
      ss = br.readLine();
      System.out.println(ss);
  }    

问题就出在  new FileInputStream(path.toString()) 使用默认字符集

而jvm在windows和linux下,读取文件的默认字符集是不同的,测试代码如下:

        Path path = Paths.get("/szc", "1.txt");
        InputStreamReader isr;
        try {
            isr = new InputStreamReader(new FileInputStream(path.toFile()));
            System.out.println("FileInputStream encoding: "+isr.getEncoding()); 
            System.out.println("File Encoding: "+System.getProperty("file.encoding"));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

上面的代码在windows下的输出结果为

FileInputStream encoding: GBK
File Encoding: GBK

而在linux上执行的结果为

FileInputStream encoding: EUC_CN
File Encoding: GB2312

其中EUC_CN 是GB2312的另一种表示方法。

另外GBK是GB2312的扩展,对于中文繁体和生僻字,GB2312无法表示。

所以就出现了在linux下用默认字符集读取"碶"字乱码,但是在windows下确没有乱码。

ps: 或许因为操作系统字符集以及版本不同,可能在jvm读取文件的默认字符集也有不同,楼主并没有做相关测试。

综上,在读取文件时,尽量指定字符集来避免操作系统差异性带来的问题。

原文地址:https://www.cnblogs.com/SamuelSun/p/5473863.html