使用java讀取磁盤文件內容容易出現亂碼, 問題是由于java使用的編碼和被讀取文件的編碼不一致導致的。(推薦:java視頻教程)
假設有一個test.txt的文本文件,文件內容為:“測試java讀取中文字符串亂碼問題”, 其中包含中文,文件的編碼格式為GBK。 假如我們使用的java平臺默認編碼為UTF-8
可使用
System.out.println(Charset.defaultCharset());
打印查看
那么當我們使用不指定編碼的方式讀取文件內容時,得到的結果將會是亂碼
String path = "C:\Users\宏鴻\Desktop\test.txt"; FileReader fileReader = new FileReader(path); char[] chars = new char[1024]; String content = ""; while (fileReader.read(chars) > 0 ) { content += new String( chars ); } System.out.println(content);
結果
然而, Java IO 系統(tǒng)Reader系列中的FileReader是沒有辦法指定編碼的,而FileReader的父類InputStreamReader可以指定編碼,所以我們可以使用它來解決亂碼問題
String path = "C:\Users\宏鴻\Desktop\test.txt"; FileInputStream fis = new FileInputStream(path); InputStreamReader inputStreamReader = new InputStreamReader(fis, "GBK"); char[] chars = new char[1024]; String content = ""; while (inputStreamReader.read(chars) > 0 ) { content += new String( chars ); } System.out.println(content);
結果
使用InputStreamReader代替FileReader,并在構造函數中指定以GBK編碼讀取FileInputStream中的內容, 便能打印正確的結果。