讀UTF-8 - BOM標記我正在通過FileReader讀取文件 - 文件是UTF-8解碼(帶BOM)現在我的問題是:我讀取文件并輸出一個字符串,但遺憾的是BOM標記也輸出了。為什么會這樣?fr = new FileReader(file);br = new BufferedReader(fr);
String tmp = null;
while ((tmp = br.readLine()) != null) {
String text;
text = new String(tmp.getBytes(), "UTF-8");
content += text + System.getProperty("line.separator");}第一行后的輸出?<style>
3 回答

紫衣仙女
TA貢獻1839條經驗 獲得超15個贊
在Java中,您必須手動使用UTF8 BOM(如果存在)。Java bug數據庫中記錄了此行為,此處和此處。暫時沒有解決方法,因為它會破壞JavaDoc或XML解析器等現有工具。在Apache的IO共享提供了一個BOMInputStream
處理這種情況。
看看這個解決方案:處理帶有BOM的UTF8文件

慕無忌1623718
TA貢獻1744條經驗 獲得超4個贊
最簡單的修復可能只是\uFEFF
從字符串中刪除結果,因為它幾乎不可能出于任何其他原因。
tmp = tmp.replace("\uFEFF", "");
另請參閱此番石榴錯誤報告

呼如林
TA貢獻1798條經驗 獲得超3個贊
使用Apache Commons庫。
類: org.apache.commons.io.input.BOMInputStream
用法示例:
String defaultEncoding = "UTF-8";InputStream inputStream = new FileInputStream(someFileWithPossibleUtf8Bom);try { BOMInputStream bOMInputStream = new BOMInputStream(inputStream); ByteOrderMark bom = bOMInputStream.getBOM(); String charsetName = bom == null ? defaultEncoding : bom.getCharsetName(); InputStreamReader reader = new InputStreamReader(new BufferedInputStream(bOMInputStream), charsetName); //use reader} finally { inputStream.close();}
- 3 回答
- 0 關注
- 561 瀏覽
相關問題推薦
添加回答
舉報
0/150
提交
取消