3

I want assert to files using char by char comparation. What the best way to do this? Without 3rd part libraries. Which file-reader is most performance for this?

amaidment
  • 6,942
  • 5
  • 52
  • 88
Ilya
  • 29,135
  • 19
  • 110
  • 158
  • 1
    How big are the files? If they are small enough then simply loading them into memory and comparing the `byte[]` with the appropriate assertion tools would probably be the easiest way. If they can be larger, then that won't work, of course. – Joachim Sauer May 25 '12 at 08:33
  • 2
    That should easily fit in memory. Note: two files can have different bytes, but have exactly the same characters. ;) – Peter Lawrey May 25 '12 at 08:51
  • 1
    And since the post is tagged with 'performance': on Java 7 you should possibly check both are the same size prior to reading (if I'm not wrong java.nio.file.Files.size(...) was introduced in Java 7). – Axel May 25 '12 at 09:13

3 Answers3

14

Not sure what the objection to 3rd party libraries is... no need to re-invent the wheel.

I've found the open-source and widely used apache.commons.io method FileUtils.contentEquals(file1, file2) is pretty good - here's the javadoc.

amaidment
  • 6,942
  • 5
  • 52
  • 88
  • is there a java 7 implementation for this function? – Thomas Jan 03 '15 at 22:38
  • @Thomas - no. Java 7 had been out for almost a year when this question was asked, and as the answer indicates, this requires a 3rd party library. – amaidment Jan 06 '15 at 18:55
2

If you happen to be using Google Guava library then you can use:

Files.equal(file1, file2);

From the docs:

Returns true if the files contains the same bytes.
Andrejs
  • 26,885
  • 12
  • 107
  • 96
1

For small files (up to a few MB), streaming I/O will yield little benefit, so you might keep things simple:

Arrays.equals(Files.readAllBytes(firstFile), Files.readAllBytes(secondFile));

If you want to use different encodings, you can also decode the bytes into characters:

boolean equal = new String(Files.readAllBytes(firstFile), firstEncoding).equals(
                new String(Files.readAllBytes(secondFile), secondEncoding));

This only requires Java 7.

meriton
  • 68,356
  • 14
  • 108
  • 175