Java FileReader 讀檔案亂碼現象
測試程式碼:
/** package com.jwen; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; /** * @author jwen * */ public class TestFileReaderAndWriter { public static void main(String[] args) { FileReader fr = null; FileWriter fw = null; try { fr = new FileReader("e:/file.txt"); } catch (FileNotFoundException e) { System.out.println("the file isn't found!"); return; } try { fw = new FileWriter("e:/file1.txt"); } catch (IOException e) { System.out.println("the file read or write errors !"); return; } int c = -1; try { while((c = fr.read()) != -1) { fw.write(c); //寫進檔案的也可能是亂碼 System.out.print((char)c); //如果你的系統不是中文的(比如英文)顯示出的文字可能會是亂碼 } fw.flush(); } catch (IOException e) { System.out.println("the file read or write errors !"); } finally { try { fr.close(); fw.close(); } catch (IOException e) { System.out.println("the file close errors !"); } } } }
原因:
你的檔案編碼預設是ANSI編碼。
不同的國家和地區制定了不同的標準,由此產生了 GB2312, BIG5, JIS 等各自的編碼標準。這些使用 2 個位元組來代表一個字元的各種漢字延伸編碼方式,稱為 ANSI 編碼。在簡體中文系統下,ANSI 編碼代表 GB2312 編碼,在日文作業系統下,ANSI 編碼代表 JIS 編碼。
不同 ANSI 編碼之間互不相容,當資訊在國際間交流時,無法將屬於兩種語言的文字,儲存在同一段 ANSI 編碼的文字中。
如果你的系統是非中文的,你的ANSI對應著相應的編碼。當讀取一個檔案中的中文時,就會出現亂碼。當然通過FileWriter寫入另一個檔案時,也會是亂碼。(因為問題出在讀取上)
解決辦法:
1 通過另一個節點流FileInputStream轉碼。
InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "GBK"); //或GB2312,GB18030
BufferedReader read = new BufferedReader(isr);
2 如非要用FileReader的話,可以將要讀取的檔案改為通用的編碼(如UTF-8).如txt的檔案可以在另存為中設定編碼。然後讀取 顯示 寫入都是正常的。
---------------------
作者:superjackson
來源:CSDN
原文:https://blog.csdn.net/w304807481/article/details/8151953
版權宣告:本文為博主原創文章,轉載請附上博文連結!