最近在讀取第三方上傳的文件時,遇到一個問題,就是採用默認字符集讀取,發現個別中文亂碼,找到亂碼的字,發現是生僻字:碶。linux
因爲在window是環境下作的測試,並無報錯,可是在linux服務器上執行,發現讀出後是亂碼。windows
具體讀取文件代碼簡化以下:服務器
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
而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下的輸出結果爲spa
FileInputStream encoding: GBK
File Encoding: GBK操作系統
而在linux上執行的結果爲code
FileInputStream encoding: EUC_CN
File Encoding: GB2312
其中EUC_CN 是GB2312的另外一種表示方法。blog
另外GBK是GB2312的擴展,對於中文繁體和生僻字,GB2312沒法表示。get
因此就出現了在linux下用默認字符集讀取"碶"字亂碼,可是在windows下確沒有亂碼。
ps: 或許由於操做系統字符集以及版本不一樣,可能在jvm讀取文件的默認字符集也有不一樣,樓主並無作相關測試。
綜上,在讀取文件時,儘可能指定字符集來避免操做系統差別性帶來的問題。