Search code examples
javainputstream

Java - Compare InputStreams of two identical files


I am creating a JUnitTest test that compares a file that is created with a benchmark file, present in the resources folder in the src folder in Eclipse.

Code

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();
    }
}
}

However, I get an Assertion Error message, without any details. Since I just created the benchmark file from the compare file operation, both files should be identical.

Thanks in advance!

EDIT: After slim's comments, I used a file diff tool and found that both files are different, although, since they are copies, I am not sure how that happened. Maybe there is a timestamp or something?


Solution

  • IOUtils.contentEquals() does not claim to give you any more information than a boolean "matches or does not match", so you cannot hope to get extra information from that.

    If your aim is just to get to the bottom of why these two files are different, you might step away from Java and use other tools to compare the files. For example https://superuser.com/questions/125376/how-do-i-compare-binary-files-in-linux

    If your aim is for your jUnit tests to give you more information when the files do not match (for example, the exception could say Expected files to match, but byte 5678 differs [0xAE] vs [0xAF]), you will need to use something other than IOUtils.contentEquals() -- by rolling your own, or by hunting for something appropriate in Comparing text files w/ Junit