【问题标题】:read UTF8 file and compare with String读取 UTF8 文件并与字符串比较
【发布时间】:2013-10-14 04:44:06
【问题描述】:

我正在尝试读取一个 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。无法弄清楚为什么。

【问题讨论】:

  • 另外:不要像这样使用getBytes(),它使用平台默认编码,这只是一个坏主意(大多数时候)。

标签: java utf-8 utf-16


【解决方案1】:

文件的开始字节:

-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"));

【讨论】:

  • 考虑到这一点,我发现了一个类似的线程stackoverflow.com/questions/9736999/…
  • @Chris 这对这里有什么帮助? OP不想处理字节[],只是字符串。并且正确的字符集声明会解决这个问题......
  • 不,正确的字符集声明没有帮助。我使用了类似版本的“checkForUtf8BOMAndDiscardIfAny”-Method 来使其工作。
猜你喜欢
  • 1970-01-01
  • 2014-10-10
  • 1970-01-01
  • 2017-08-20
  • 2011-04-07
  • 2011-10-24
  • 1970-01-01
  • 1970-01-01
  • 2020-03-20
相关资源
最近更新 更多