Java Reference
In-Depth Information
try {
boolean isSame = Files.isSameFile(p1, p2);
System.out.println("p1 and p2 are the same: " + isSame);
isSame = Files.isSameFile(p3, p4);
System.out.println("p3 and p4 are the same: " + isSame);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
p1 and p2 are the same: true
p3 and p4 are the same: true
Normalizing, Resolving, and Relativizing Paths
In a file system, it is common to use a dot and two dots to represent the current directory and the parent directory,
respectively. Sometimes it is also acceptable to specify more than one consecutive delimiter between a file name
and a directory name. The normalize() method of the Path interface returns a Path after removing these extra
characters. This method does not access the file system. Sometimes a normalized path may not locate the same file as
the original path if the original path contained a symbolic link. The following snippet of code shows some examples
of normalizing paths on Windows. Please change the paths to conform to your platform if you run this code on a
platform other than Windows.
Path p1 = Paths.get("C:\\poems\\..\\\\poems\\luci1.txt");
Path p1n = p1.normalize();
System.out.println(p1 + " normalized to " + p1n);
Path p2 = Paths.get("C:\\poems\\luci1.txt");
Path p2n = p2.normalize();
System.out.println(p2 + " normalized to " + p2n);
Path p3 = Paths.get("a\\..\\.\\test.txt");
Path p3n = p3.normalize();
System.out.println(p3 + " normalized to " + p3n);
C:\poems\..\poems\luci1.txt normalized to C:\poems\luci1.txt
C:\poems\luci1.txt normalized to C:\poems\luci1.txt
a\..\.\test.txt normalized to test.txt
You can combine two paths using the resolve(Path p) method of the Path interface. If the specified path is an
absolute path, it returns the specified path. It returns the path if the specified path is an empty path. In other cases,
it simply combines the two paths and returns the result, so the returned path ends with the specified path. The path
on which this method is invoked is assumed to be a directory. The following snippet of code has some examples of
resolving paths on Windows. Please change the paths to conform to your platform if you run this code on a platform
other than Windows.
 
Search WWH ::




Custom Search