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