A canonical pathname is both absolute and unique. The precise
definition of canonical form is system-dependent. This method first
converts this pathname to absolute form if necessary, as if by invoking the
{@link #getAbsolutePath} method, and then maps it to its unique form in a
system-dependent way. This typically involves removing redundant names
such as <tt>"."</tt> and <tt>".."</tt> from the pathname, resolving
symbolic links (on UNIX platforms), and converting drive letters to a
standard case (on Microsoft Windows platforms).
Every pathname that denotes an existing file or directory has a
unique canonical form. Every pathname that denotes a nonexistent file
or directory also has a unique canonical form. The canonical form of
the pathname of a nonexistent file or directory may be different from
the canonical form of the same pathname after the file or directory is
created. Similarly, the canonical form of the pathname of an existing
file or directory may be different from the canonical form of the same
pathname after the file or directory is deleted.
以上是java源码对canonicalpath的解释。大致意思为:
1.获取绝对路径,windows系统下去掉”.”或者”..”,盘符标准化;unix系统下,处理下符号链接
2.不存在文件或文件夹的规范名可能跟该文件创建后的规范名不同
代码:
File file = new File("../");
File file1 = new File("e:/test.txt");
try {
System.out.println("规范名: "+file.getCanonicalPath());
System.out.println("绝对路径: "+file.getAbsolutePath());
System.out.println("规范: "+file1.getCanonicalPath());
System.out.println("绝对: "+file1.getAbsolutePath());
} catch (IOException e) { e.printStackTrace(); }
输出:
规范名: E:\eclipse-workspace
绝对路径: E:\eclipse-workspace\howtomcatworks_excercise\..
规范: E:\test.txt
绝对: e:\test.txt
网友评论