2013-10-07 111 views
0

比較我正在嘗試讀取UTF8文本文件,然後使用equals()應該返回true來進行文本比較。但它不,因爲getBytes()返回不同的值。讀取UTF8文件並與字符串

這是一個小例子:

public static void main(String[] args) throws Exception { 
    System.out.println(Charset.defaultCharset()); // UTF-8 
    InputStream is = new FileInputStream("./myUTF8File.txt"); 
    BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF8")); 
    String line; 
    while ((line = in.readLine()) != null) { 
    System.out.print(line); // mouseover 
    byte[] bytes = line.getBytes(); // [-17, -69, -65, 109, 111, 117, 115, 101, 111, 118, 101, 114] 
    String str = "mouseover"; 
    byte[] bytesStr = str.getBytes(); // [109, 111, 117, 115, 101, 111, 118, 101, 114] 
    if (line.equals(str)) { // false 
     System.out.println("equal"); 
    } 
    } 
} 

我會期望String爲convertet爲UTF-16在line.readLine()和等於返回true。無法弄清楚原因。

+1

另外:不要像這樣使用'getBytes()',它使用平臺的默認編碼,這只是一個簡單的壞主意(大部分時間)。 –

回答

3

的文件的開頭字節:

-17, -69, -65 

是字節BOM: Byte Order Mark ...您的數據的一些相關性:

[-17, -69, -65, 109, 111, 117, 115, 101, 111, 118, 101, 114] 
       [109, 111, 117, 115, 101, 111, 118, 101, 114] 

此外,字符集的正確名稱是"UTF-8" - 注意破折號

BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8")); 
+0

考慮到這一點,我發現了一個類似的線程http://stackoverflow.com/questions/9736999/how-to-remove-bom-from-an-xml-file-in-java – Kalle

+0

@Chris這是如何幫助這裏? OP不想處理字節[],只是字符串。而正確的字符集聲明照顧... – ppeterka

+0

不,正確的字符集聲明沒有幫助。我使用了類似版本的「checkForUtf8BOMAndDiscardIfAny」 - 方法來使其工作。 – Kalle

相關問題