how to check if two filename paths refer to the same file?
I just found out the information that a filename path may include redundant names such as ‘.’ or ‘..’ or symbolic links (on UNIX platforms).
so how to know exactly if two filename paths are referring to the same file?
use File.getCanonicalFile() to convert a filename path to a unique canonical form suitable for comparisons. and then, compare the results of both getCanonicalFile() with equals(…)
just take a look at this example below to get some idea.
public boolean isSameFile() {
File file1 = new File("./filename");
File file2 = new File("filename");
// Filename paths are not equal
// false, don't use this way to compare.
boolean b = file1.equals(file2);
// Normalize the paths first.
try {
// D:\\sth\\filename
file1 = file1.getCanonicalFile();
// also D:\\sth\\filename
file2 = file2.getCanonicalFile();
} catch (IOException e) {
// your exception lines...
}
// Filename paths are now equal.
return file1.equals(file2); // true
}
I got this information from www.exampledepot.com there are more interesting tips about file handling in Java programming. just make sure you won’t miss those tips too.
have a nice day of coding.
