Determine if two file paths refer to the same file

From CodeCodex

Revision as of 19:23, 22 July 2010 by 211.2.129.92 (Talk)

Implementations

Java

A filename path may include redundant names such as `.' or `..' or symbolic links (on UNIX platforms). File.getCanonicalFile() converts a filename path to a unique canonical form suitable for comparisons.

    File file1 = new File("./filename");
    File file2 = new File("filename");
    
    // Filename paths are not equal
    boolean b = file1.equals(file2);      // false
    
    // Normalize the paths
    try {
        file1 = file1.getCanonicalFile(); // c:\almanac1.4\filename
        file2 = file2.getCanonicalFile(); // c:\almanac1.4\filename
    } catch (IOException e) {
    }
    
    // Filename paths are now equal
    b = file1.equals(file2);              // true

Ruby

Converts a pathname to an absolute pathname and compares them.

def same_path?(path1, path2)
  path1 = File.expand_path(path1)
  path2 = File.expand_path(path2)
  path1 == path2
end

p same_path?("./filename", "filename")  #=> true