读取UTF8文件并与String进行比较

时间:2013-10-07 14:41:15

标签: java utf-8 utf-16

我正在尝试读取UTF8文本文件,然后使用应返回true的equals()进行文本比较。但它没有,因为getBytes()返回不同的值。

这是一个最小的例子:

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在line.readLine()处转换为UTF-16,并且equals返回true。无法弄清楚为什么。

1 个答案:

答案 0 :(得分: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"));