IT科技

當前位置 /首頁/IT科技 > /列表

fileinputstream中文亂碼

Java中使用 FileInputStream 讀取txt等文檔時,中文會產生亂碼,這是因為一箇中文對應兩個字節存儲(負數),也就是説,讀取對應中文的字節數應該是偶數; 而英文對應一個字節存儲。FileInputStream每次讀取一個數組長度的字節時,讀取的中文字節數可能是奇數,也就是隻讀到中文的一半字節,出現亂碼。

fileinputstream中文亂碼

解決方法是:

try {

            fis = new FileInputStream(file);

            InputStreamReader reader = new InputStreamReader(fis,"GBK"); //最後的"GBK"根據文件屬性而定,如果不行,改成"UTF-8"試試 BufferedReader br = new BufferedReader(reader); String line; while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); reader.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } }

fileinputstream中文亂碼 第2張

關於解決fileinputstream中文亂碼問題,我們就瞭解到這啦!