Link Option
The enum type LinkOption defines how symbolic links should be handled by a file operation. This enum type defines only one constant, shown in Table 21.6. If the constant NOFOLLOW_LINKS is specified in a method call, symbolic links are not followed by the method.
The enum type LinkOption implements both the CopyOption interface (p. 1308) and the OpenOption interface (p. 1314). Many file operations declare a variable arity parameter of one of these interface types or just the enum type LinkOption, making it possible to configure their operation.
Table 21.6 Link Option
Enum java.nio.file.LinkOption implements the java.nio.file.CopyOption and the java.nio.file.OpenOption interfaces | Description |
NOFOLLOW_LINKS | Do not follow symbolic links. |
Converting a Path to a Real Path
The toRealPath() method of the Path interface converts this path to an absolute path that denotes the same directory entry as this path. The name elements in the path must represent actual directories in the file system or the method throws an IOException. It accepts a variable arity parameter of the enum type java.nio.file.LinkOption (Table 21.6). If the variable arity parameter is not specified, symbolic links are followed to their final target.
The toRealPath() method performs several operations to construct the real path:
- If this path is a relative path, it is first converted to an absolute path.
- Any redundant name elements are removed to create a new path. In other words, it normalizes the result path.
- If LinkOption.NOFOLLOW_LINKS is specified, any symbolic links are not followed.
Table 21.7 show the results of calling the toRealPath() method on selected paths. Since the method throws an IOException, it should typically be called in a try-catch construct.
try {
Path somePath = Path.of(“some/path”);
Path realPath = somePath.toRealPath(LinkOption.NOFOLLOW_LINKS);
System.out.println(realPath);
} catch (NoSuchFileException nsfe) {
nsfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
Table 21.7 Converting to a Real Path
Current directory: /book/chap01 The symbolic link ./alias_appendixA has the target /book/appendixA. | Text representation of the Path returned by the toRealPath() method | |
(1) | Path currDir = Path.of(“.”); | /book/chap01 |
(2) | Path parentDir = Path.of(“..”); | /book |
(3) | Path path3 = Path.of(“./examples/.././examples/D.java”); | /book/chap01/examples/D.java |
(4) | Path path4 = Path.of(“./alias_appendixA”); | path4.toRealPath() returns /book/appendixA. path4.toRealPath(LinkOption. NOFOLLOW_LINKS) returns /book/chap01/alias_appendixA. |
Leave a Reply