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?
Asked
Active
Viewed 5,244 times
3
-
1How 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
-
2That 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
-
1And 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 Answers
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
-
-
@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
-
There is no [equals](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/Files.html). – wener Dec 19 '15 at 18:52
-
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