0

我正在尝试读取一个 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");
    }
  }
}

我希望字符串在 line.readLine() 处转换​​为 UTF-16,并且等于返回 true。无法弄清楚为什么。

4

1 回答 1

3

文件的开始字节:

-17, -69, -65

BOM 的字节:字节顺序标记...您的数据的一些相关性:

[-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"));
于 2013-10-07T14:44:14.593 回答