【发布时间】:2022-11-21 20:43:55
【问题描述】:
我比较两个文件的内容如下:
byte[] expectedContent = Files.readAllBytes(expectedPath);
byte[] generatedContent = Files.readAllBytes(generatedPath);
Assertions.assertTrue(Arrays.equals(expectedContent, generatedContent), "Content not equal)
IntelliJ 显示这两个文件是相同的(关于空白、格式等)
也逐行比较工作正常。
Scanner input1 = new Scanner(new File(expectedPath.toString()));
Scanner input2 = new Scanner(new File(generatedPath.toString()));
while(input1.hasNextLine() && input2.hasNextLine()){
String first = input1.nextLine();
String second = input2.nextLine();
Assertions.assertTrue(first.equals(second), "Differences found: "+"\n"+first+'\n'+second);
}
但是,比较字节数组(expectedContent 和generatedContent)失败。这是为什么? readAllBytes 是否读取了一些元数据?
【问题讨论】:
-
“比较字节数组文件”=> 你是什么意思?
-
@assylias sry 打错了。
-
我建议使用可以向您显示每个文件的哈希或校验和的工具......我的猜测是它们确实不同,也许只是换行符(CRLF vs LF)
-
您的逐行比较代码有一个明显的缺陷:它无法报告一个文件是否是另一个文件的子集。例如如果一个文件只有一行而另一个文件为空,则 while 循环将永远不会执行。
-
遍历数组内容并打印任何不同的索引和字节(在确保长度相等之后)。