比較我正在嘗試讀取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。無法弄清楚原因。
另外:不要像這樣使用'getBytes()',它使用平臺的默認編碼,這只是一個簡單的壞主意(大部分時間)。 –