an3*_*nto 6 java string byte equals
尝试将图像从客户端发送到服务器时,我遇到了一些麻烦,因为原始图像与收到的图像不同.为了找到问题,我正在逐行阅读两个图像寻找差异.当我逐行比较字符串时,对于某些使用String#equals的行(例如lineo.equals(lined)),结果为false,但是当我在控制台中打印它们时它们似乎相同,我也比较它们的字节阵列.令人惊讶的是,使用Array.equals(lineo.getBytes(),lined.getBytes())结果为true.客户端和服务器都在同一台计算机上.
请帮我理解
为什么两种方法都要比较,返回不同的结果
private void compareImages() throws IOException {
File dest = new File("C:\\TempFiles\\" + fileName);
File orig = new File("C:\\Users\\Andres\\Desktop\\B&N\\" + fileName);
BufferedReader bro = new BufferedReader(new FileReader(orig));
BufferedReader brd = new BufferedReader(new FileReader(dest));
String lineo = bro.readLine();
String lined = brd.readLine();
System.out.println("Ready to read");
while (lineo!= null && lined!= null) {
if(!lined.equals(lineo))
{
System.out.println("lineo");
System.out.println(lineo);
System.out.println("lined");
System.out.println(lined);
System.out.println("arrayo");
System.out.println(printArray(lineo.getBytes()));
System.out.println("arrayd");
System.out.println(printArray(lined.getBytes()));
System.out.println("Are: " + Arrays.equals(lined.getBytes(), lineo.getBytes()));
break;
}
lineo = bro.readLine();
lined = brd.readLine();
}
bro.close();
brd.close();
}
public String strArray(byte[] array){
String toRet = "";
for (byte b : array) {
toRet += b;
}
return toRet;
}
Run Code Online (Sandbox Code Playgroud)
控制台的结果是:
LINEO
ÿÄμ}!AQa"q2?'¡#B±ÁRÑð$ 3br,
夹
ÿÄμ}!AQa"q2?'¡#B±ÁRÑð$ 3br,
arrayo
11-1-600-751602133243554400112512304175183349656198197734113205063-111-9583566-79-632182-47-16365198114-1269
arrayd
11-1-600-751602133243554400112512304175183349656198197734113205063-111-9583566-79-632182-47-16365198114-1269
是:真的
请记住,我无法从输出中复制一些字符.
问候,
安德烈斯
当你这样做时,不相等的字符串不必产生不同的数组getBytes().
结果取决于平台的默认字符集,但是当我运行以下代码时
String str1 = "?";
byte[] arr1 = str1.getBytes();
String str2 = "\u0080";
byte[] arr2 = str2.getBytes();
System.out.println(str1.equals(str2));
System.out.println(Arrays.equals(arr1, arr2));
Run Code Online (Sandbox Code Playgroud)
我看到的输出是
false
true
Run Code Online (Sandbox Code Playgroud)
我不确切知道这里发生了什么,但看起来某些控制字符被视为'?'.
理解字符串不同的正确方法是比较返回的字符数组toCharArray().
| 归档时间: |
|
| 查看次数: |
2882 次 |
| 最近记录: |