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?
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));
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.
It seems like I have to write my own equals method to support it, right?
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.