Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if two files store the same content

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.

like image 265
principal-ideal-domain Avatar asked Dec 09 '14 12:12

principal-ideal-domain


People also ask

How can I tell if two files have the same content?

Probably the easiest way to compare two files is to use the diff command. The output will show you the differences between the two files. The < and > signs indicate whether the extra lines are in the first (<) or second (>) file provided as arguments. In this example, the extra lines are in backup.

How do I compare data between two files?

From the Micro Focus Data File Tools window, click Tools > Compare Files. The File Compare dialog box appears. and select the required file.


1 Answers

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.
like image 161
SMA Avatar answered Sep 21 '22 08:09

SMA