This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

What is the difference between getPath (), getAbsolutePath () and getCanonicalPath () in Java? 支那

What is the difference between getPath (), getAbsolutePath () and getCanonicalPath () in Java? And when to choose which one is better?

Answer 1:

Practice is the sole criterion for testing truth.

import java.io.File;
public class PathTesting {
    public static void main(String [] args) {
        File f = new File("test/.. /./file.txt");
        System.out.println(f.getPath());
        System.out.println(f.getAbsolutePath());
        try {
            System.out.println(f.getCanonicalPath());
        }
        catch(Exception e) {}
    }
}
Copy the code

Using the code above produces the following output:

test\.. \.\file.txt C:\projects\sandbox\trunk\test\.. \.\file.txt C:\projects\sandbox\trunk\file.txtCopy the code

From what has been discussed above

GetPath () gives you the path based on the File object, which may or may not be relative;

GetAbsolutePath () provides you with the absolute path to the file;

3, getCanonicalPath() after parsing any relative paths for the current directory, gets the path string and deletes all relative paths (. And..) , and any file system link returns a path that the file system considers to be the canonical method of referring to the file system object to which it points.

Note that there are a large number of absolute paths to the same file, but only one canonical path.

For example

C:\temp\file. TXT – This is a path, an absolute path and a canonical path.

.\file.txt- This is a path. It is neither an absolute path nor a canonical path.

C:\temp\myapp\bin.. \.. \file.txt- This is a path and an absolute path. This is not a normative path.

The canonical path is always an absolute path.

The article translated from Stack Overflow: stackoverflow.com/questions/1…