關於Android中的亂碼

來源:互聯網
上載者:User

在寫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的編碼格式,這個就要求你要事Crowdsourced Security Testing道assets檔案的編碼格式。
比如我的assets檔案sources.lws檔案是利用搜狗IME(可以設定字元集)編寫的,預設字元集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

 


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.