[英]java how to distinguish a file encoding ISO-8859-1 and UTF-8?
我有一個Android應用程序,它使用SQL腳本讀取文件以將數據插入SQLite DB。 但是我需要知道這個文件的編碼,我有一個EditText可以從SQLite讀取信息,如果編碼不正確,它將顯示為無效字符,例如“?”。 而不是“ç,í,ã”之類的字符。
我有以下代碼:
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn, "ISO-8859-1"));
String aDataRow;
while ((aDataRow = myReader.readLine()) != null) {
if(!aDataRow.isEmpty()){
String[] querys = aDataRow.split(";");
Collections.addAll(querysParaExecutar, querys);
}
}
myReader.close();
這適用於“ ISO-8859-1”編碼,如果我將“ UTF-8”設置為字符集,則適用於UTF-8。 我需要以編程方式檢測字符集編碼(UTF-8或ISO-8859-1),並將正確的編碼應用於我的代碼。 有沒有簡單的方法可以做到這一點?
我解決了lib通用chardet的問題。 一切正常。
FileInputStream fIn = new FileInputStream(myFile);
byte[] buf = new byte[4096];
UniversalDetector detector = new UniversalDetector(null);
int nread;
while ((nread = fIn.read(buf)) > 0 && !detector.isDone()) {
detector.handleData(buf, 0, nread);
}
detector.dataEnd();
String encoding = detector.getDetectedCharset();
String chartsetName = null;
if (encoding.equalsIgnoreCase("WINDOWS-1252")){
chartsetName = "ISO-8859-1";
}
if (encoding.equalsIgnoreCase("UTF-8")){
chartsetName = "UTF-8";
}
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn, chartsetName));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.