在寫Android應用時經常會遇到讀取亂碼的問題,這裡總結下我所遇到的亂碼相關問題:
首先,我用的是Eclipse集成開發環境,剛開始時在.java文件中含有漢字時,Eclipse會報出不能識別編碼的錯誤,這個問題的解決辦法是修改Eclipse的編碼配置,方法是:
點擊"Windows"->"Preferences"->"General"->"Content Types",把"Java Source File"的"Default encoding"配置為支持漢字的編碼格式,我的修改為utf-8,還可以修改為utf-16,GBK等。
其他得與開發環境相關的亂碼問題一般都可以在這裡解決,比如修改xml文件的配置格式等。
然後,又遇到瞭讀取assets文件的亂碼問題,因為Android讀取文件時,如果沒有正確設置讀取格式,Android會利用默認的編碼格式來讀取,如果assets文件的編碼格式與Android的默認格式不相符,就會出現亂碼問題,這個問題的解決辦法為:
在利用InputStreamReader讀取文件的InputStream時,設置讀取的編碼格式為assets的編碼格式,這個就要求你要事先知道assets文件的編碼格式。
比如我的assets文件sources.lws文件是利用搜狗輸入法(可以設置字符集)編寫的,默認字符集GBK,然後就可以利用以下代碼獲取讀取sources.lws的BufferedReader:
is = getResources().getAssets().open("library.lws");
BufferedReader br=new BufferedReader(new InputStreamReader(is,"GBK"));
然後就可以利用BufferedReader讀取文件中的字符瞭(當然你也可以直接用InputStreamReader)。
這種方法比較簡單,但是你必須知道所要打開的文件的編碼格式。
如果事先不知道編碼格式,也可以先讀取幾個字節的數據來判斷文件所用的編碼格式。這就要利用到各種編碼格式的特點。
File file = new File(filepath);
BufferedReader reader;
String text = "";
FileInputStream fis = new FileInputStream(file);
BufferedInputStrea min = new BufferedInputStream(fis);
in.mark(4);
byte[]first3bytes = new byte[3];
in.read(first3bytes);
in.reset();
if(first3bytes[0] == (byte) 0xEF && first3bytes[1] == (byte) 0xBB
&&first3bytes[2] == (byte) 0xBF) {// utf-8
reader = new BufferedReader(newInputStreamReader(in, "utf-8"));
}else if (first3bytes[0] == (byte) 0xFF
&&first3bytes[1] == (byte) 0xFE) {
reader = new BufferedReader(
new InputStreamReader(in,"unicode"));
}else if (first3bytes[0] == (byte) 0xFE
&&first3bytes[1] == (byte) 0xFF) {
reader = new BufferedReader(newInputStreamReader(in,
"utf-16be"));
}else if (first3bytes[0] == (byte) 0xFF
&&first3bytes[1] == (byte) 0xFF) {
reader = new BufferedReader(newInputStreamReader(in,
"utf-16le"));
}else {
reader = new BufferedReader(newInputStreamReader(in, "GBK"));
}
這段代碼可以判斷文件的編碼格式,然後針對不同格式創建不同的BufferedReader來讀取文件。
作者:tobacco5648