Java Reference
In-Depth Information
You can use the toRealPath() method to get the real path of an existing file. It returns a canonical path to an
existing file. If the path represents a symbolic link, it returns the real path of the target file. You can pass a link option
to this method indicating whether you do not want to follow the symbolic link to its target. If the file represented by
the path does not exist, the toRealPath() throws an IOException . The following snippet of code demonstrates how to
get the real path from a Path object:
import java.io.IOException;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
...
try {
Path p2 = Paths.get("test2.txt");
// Follow link for p2, if it is a symbolic link
Path p2RealPath = p2.toRealPath();
System.out.println("p2RealPath:" + p2RealPath);
}
catch (IOException e) {
e.printStackTrace();
}
try {
Path p3 = Paths.get("test3.txt");
// Do not follow link for p3, if it is a symbolic link
Path p3RealPath = p3.toRealPath(LinkOption.NOFOLLOW_LINKS);
System.out.println("p3RealPath:" + p3RealPath);
}
catch (IOException e) {
e.printStackTrace();
}
You can use the toUri() method of a Path object to get its URI representation. A URI representation of a path is
highly platform-dependent. Typically, a URI form of a path can be used in a browser to open the file indicated by the
path. The following snippet of code shows how to get the URI form of a path. The output was generated on Windows.
You may get a different output.
Path p2 = Paths.get("test2.txt");
java.net.URI p2UriPath = p2.toUri();
System.out.println("Absolute Path: " + p2.toAbsolutePath());
System.out.println("URI Path: " + p2UriPath);
Absolute Path: C:\java_code\testapp\test2.txt
URI Path: file:///C:/java_code/testapp/test2.txt
 
Search WWH ::




Custom Search