区分getPath(), getAbsolutePath(), getCanonicalPath()

区分getPath(), getAbsolutePath(), getCanonicalPath()

来自

http://stackoverflow.com/questions/1099300/whats-the-difference-between-getpath-getabsolutepath-and-getcanonicalpath

C:\temp\file.txt" - this is a path, an absolute path, a canonical path

.\file.txt This is a path, It's not an absolute path nor canonical path.

C:\temp\myapp\bin\..\\..\file.txt This is a path, and an absolute path, it's not a canonical path

Canonical path is always an absolute path.

Converting from a path to a canonical path makes it absolute (通常会处理改变当前目录,所以像. ./file.txt 变为c:/temp/file.txt). The canonical path of a file just "purifies" the path, 去除和解析类似“ ..\” and resolving symlinks(on unixes)

In short:

  • getPath() gets the path string that the File object was constructed with, and it may be relative current directory.
  • getAbsolutePath() gets the path string after resolving it against the current directory if it's relative, resulting in a fully qualified path.
  • getCanonicalPath() gets the path string after resolving any relative path against current directory, and removes any relative pathing (. and ..), and any file system links to return a path which the file system considers the canonical means to reference the file system object to which it points.

Also, each of this has a File equivalent which returns the corresponding File object.

The best way I have found to get a feel for things like this is to try them out:

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) {}
        }
}

Your output will be something like:

test\..\.\file.txt
C:\projects\sandbox\trunk\test\..\.\file.txt
C:\projects\sandbox\trunk\file.txt

So, getPath() gives you the path based on the File object, which may or may not be relative; getAbsolutePath() gives you an absolute path to the file; and getCanonicalPath() gives you the unique absolute path to the file. Notice that there are a huge number of absolute paths that point to the same file, but only one canonical path.

When to use each? Depends on what you're trying to accomplish, but if you were trying to see if two Files are pointing at the same file on disk, you could compare their canonical paths.

你可能感兴趣的:(区分getPath(), getAbsolutePath(), getCanonicalPath())