Alex Rivera | Logout

Java, Linux: how to detect whether two java.io.Files refer to the same physical file

Asked 2011-05-04T12:18:23.590
9

I'm looking for an efficient way to detect whether two java.io.Files refer to the same physical file. According to the docs, File.equals() should do the job:

Tests this abstract pathname for equality with the given object. Returns true if and only if the argument is not null and is an abstract pathname that denotes the same file or directory as this abstract pathname.

However, given a FAT32 partition (actually a TrueCrypt container) which is mounted at /media/truecrypt1:

new File("/media/truecrypt1/File").equals(new File("/media/truecrypt1/file")) == false

Would you say that this conforms to the specification? And in this case, how to work around that problem?

Update: Thanks to commenters, for Java 7 I've found java.io.Files.isSameFile() which works for me.

Edit
Report

1 Answer

3

you could try to obtain an exclusive write lock on the file, and see if that fails:

boolean isSame;
try {
   FileOutputStream file1 = new FileOutputStream (file1);
   FileOutputStream file2 = new FileOutputStream (file2);
   FileChannel channel1 = file1.getChannel();
   FileChannel channel2 = file2.getChannel();
   FileLock fileLock1 = channel1.tryLock();
   FileLock fileLock2 = channel2.tryLock();
   isSame = fileLock2 != null;
} catch(/*appropriate exceptions*/) {
   isSame = false;
} finally {
   fileLock1.unlock();
   fileLock2.unlock();
   file1.close();
   file2.close();
   ///cleanup etc...
}
System.out.println(file1 + " and " + file2 + " are " + (isSame?"":"not") + " the same");

This is not always guaranteed to be correct tho - because another process could potentially have obtained the lock, and thus fail for you. But at least this doesn't require you to shell out to an external process.

answered 2011-05-04T13:15:01.650

Your Answer