Java – Determine if two files store the same content

comparisonfilejava

How would you write a java function boolean sameContent(Path file1,Path file2)which determines if the two given paths point to files which store the same content? Of course, first, I would check if the file sizes are the same. This is a necessary condition for storing the same content. But then I'd like to listen to your approaches. If the two files are stored on the same hard drive (like in most of my cases) it's probably not the best way to jump too many times between the two streams.

Best Answer

Exactly what FileUtils.contentEquals method of Apache commons IO does and api is here.

Try something like:

File file1 = new File("file1.txt");
File file2 = new File("file2.txt");
boolean isTwoEqual = FileUtils.contentEquals(file1, file2);

It does the following checks before actually doing the comparison:

  • existence of both the files
  • Both file's that are passed are to be of file type and not directory.
  • length in bytes should not be the same.
  • Both are different files and not one and the same.
  • Then compare the contents.