Java - 比较两个相同文件的输入流

Java - Compare InputStreams of two identical files

我正在创建一个 JUnitTest 测试,将创建的文件与基准文件进行比较,基准文件位于 Eclipse src 文件夹的资源文件夹中。

代码

public class CompareFileTest
{
    private static final String TEST_FILENAME = "/resources/CompareFile_Test_Output.xls";

@Test
public void testCompare()
{
    InputStream outputFileInputStream = null;
    BufferedInputStream bufferedInputStream = null;

    File excelOne = new File(StandingsCreationHelper.directoryPath + "CompareFile_Test_Input1.xls");
    File excelTwo = new File(StandingsCreationHelper.directoryPath + "CompareFile_Test_Input1.xls");
    File excelThree = new File(StandingsCreationHelper.directoryPath + "CompareFile_Test_Output.xls");

    CompareFile compareFile = new CompareFile(excelOne, excelTwo, excelThree);

    // The result of the comparison is stored in the excelThree file
    compareFile.compare();

    try
    {
        outputFileInputStream = new FileInputStream(excelThree);
        bufferedInputStream = new BufferedInputStream(outputFileInputStream);

        assertTrue(IOUtils.contentEquals(CompareFileTest.class.getResourceAsStream(TEST_FILENAME), bufferedInputStream));
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}
}

但是,我收到断言错误消息,没有任何详细信息。由于我刚刚通过比较文件操作创建了基准文件,因此两个文件应该相同。

提前致谢!

编辑:在 slim 的评论之后,我使用了一个文件差异工具,发现两个文件是不同的,但是,由于它们是副本,我不确定这是怎么发生的。也许有时间戳之类的?

IOUtils.contentEquals() 并没有声称可以为您提供比布尔值 "matches or does not match" 更多的信息,因此您不能指望从中获得额外的信息。

如果您的目标只是弄清这两个文件不同的原因,您可能会放弃 Java 并使用其他工具来比较文件。例如https://superuser.com/questions/125376/how-do-i-compare-binary-files-in-linux

如果您的目标是让您的 jUnit 测试在文件不匹配时为您提供更多信息(例如,异常可能是 Expected files to match, but byte 5678 differs [0xAE] vs [0xAF]),您将需要使用 [=10 以外的东西=] -- 通过自己滚动,或者在 Comparing text files w/ Junit

中寻找合适的东西

我遇到了类似的问题。

我正在使用 JUNIT 断言库 Assertions 并得到了正在比较的内存地址,而不是它看起来的实际文件。

我没有比较 InputStream 对象,而是将它们转换为字节数组并进行了比较。不是绝对的特价,但我敢断言,如果字节数组是相同的,那么底层 InputStream 和它的文件有很大的机会是相等的。

像这样:

 Assertions.assertEquals(
            this.getClass().getResourceAsStream("some_image_or_other_file.ext").readAllBytes(),
            someObject.getSomeObjectInputStream().readAllBytes());

不确定这是否适用于更大的文件。对于复杂的差异当然不合适,但它可以解决断言问题。