在改寫V&View(維視)時用到了文件管理,需要從html文檔讀取字符串,可是一直出現中文亂碼,一直解決不了.而且很是意外,我在本地運行代碼時就能正常讀取中文,當放到tomcat上時全是亂碼,這也讓我清醒的意識到了本地開發環境和在線調試環境一致的重要性了.我的tomcat沒有設置字符串編碼,默認是ISO-8859-1,而我的html是utf-8的,這就存在一個不一致的問題了。兩種解決方法:
方法一,設置tomcat字符編碼為utf-8,這種方法缺點很大,要是哪天重裝了tomcat又忘了設置了,那就大大的bug了~所以我直接跳過,
方法二,代碼中進行編碼轉換,我使用的是BufferedReader,中間加一個InputStreamReader進行編碼轉換,這下總不會亂碼了吧!呵呵,上代碼:
public static String readFileByLines(String fileName) {
FileInputStream file = null;
BufferedReader reader = null;
InputStreamReader inputFileReader = null;
String content = "";
String tempString = null;
try {
file = new FileInputStream(fileName);
inputFileReader = new InputStreamReader(file, "utf-8");
reader = new BufferedReader(inputFileReader);
// 一次讀入一行,直到讀入null為文件結束
while ((tempString = reader.readLine()) != null) {
content += tempString;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
return content;
}