使用java讀取磁盤文件內(nèi)容容易出現(xiàn)亂碼, 問題是由于java使用的編碼和被讀取文件的編碼不一致導(dǎo)致的。(推薦:java視頻教程)
假設(shè)有一個(gè)test.txt的文本文件,文件內(nèi)容為:“測試java讀取中文字符串亂碼問題”, 其中包含中文,文件的編碼格式為GBK。 假如我們使用的java平臺(tái)默認(rèn)編碼為UTF-8
可使用
System.out.println(Charset.defaultCharset());
打印查看
那么當(dāng)我們使用不指定編碼的方式讀取文件內(nèi)容時(shí),得到的結(jié)果將會(huì)是亂碼
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);
結(jié)果
然而, 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);
結(jié)果
使用InputStreamReader代替FileReader,并在構(gòu)造函數(shù)中指定以GBK編碼讀取FileInputStream中的內(nèi)容, 便能打印正確的結(jié)果。