I don't know about you guys but at least I expected that f1 would be equal to f2 in the below code but apparently that's not the case! What's your thoughts about this? It seems like I have to write my own equals method to support it, right?
import java.io.*;
public class FileEquals
{
public static void main(String[] args)
{
File f1 = new File("./hello.txt");
File f2 = new File("hello.txt");
System.out.println("f1: " + f1.getName());
System.out.println("f2: " + f2.getName());
System.out.println("f1.equals(f2) returns " + f1.equals(f2));
System.out.println("f1.compareTo(f2) returns " + f1.compareTo(f2));
}
}
Here is the implementation of both methods:
If you just want to check if the files are the same based on their path use
java.nio.file.Files#isSameFile
E.g.
If you are using windows see class
Win32FileSystem
The comparison method is like below, so it is very normal that your file objects are different.
Add those lines to your code as well
and it will print
Hence they are not equal as the comparison is made using path proeprty of File object
To properly test equals, you must call getCanonicalFile(). e.g.
Will return true for equals. Note that getCanonicalFile may throw an IOException so I added that to the method signature.
The quicker way I found to diff on two files is below.
That's just proposition to work it around.
Not sure about the performance (what if files are 10 GB each?)
EDIT
But still, diff utility on unix system would be much quicker and verbose. Depends what you need to compare.
Not, it's not the case. Because equals is comparing equality of absolute paths (in your case above it is something like:
So they are naturally different.
Probably yes. But first of all, you have to know what you want to compare? Only pathnames? If yes, compare its canonical path in this way:
But if you want compare content of two different files, then yes, you should write your own method - or simply just copy from somewhere on the internet.