Java Reference
In-Depth Information
Operations on a symbolic link are transparent to the application. When an operation is performed on a symbolic
link, the operating system performs the operation on the target of the link. For example, performing a read/write
operation on a symbolic link performs a read/write on its target. However, the delete, move, and rename operations
are performed directly on the link, rather than on its target. Sometimes it is possible to have a circular reference in a
symbolic link, where the target of a symbolic link points back to the original link.
The NIO.2 API fully supports symbolic links. It has safeguards in place to detect a circular reference in a symbolic
link. You can work with symbolic links using the
java.nio.file.Files
class. You can use its
isSymbolicLink(Path p)
method to check if the file denoted by the specified path is a symbolic link. The
createSymbolicLink()
method of the
Files
class is used to create a symbolic link. Note that the
createSymbolicLink()
is an optional operation, which may
not be supported on all platforms.
Path existingFilePath = Paths.get("C:\\poems\\luci1.txt");
Path symLinkPath = Paths.get("C:\\luci1_link.txt");
try {
Files.createSymbolicLink(symLinkPath, existingFilePath);
}
catch (IOException e) {
e.printStackTrace();
}
The NIO.2 API follows the symbolic link by default. In some cases, you can specify whether you want to follow a
symbolic link or not. The option not to follow a symbolic link is indicated by using the enum constant
LinkOption.
NOFOLLOW_LINKS
. The
LinkOption
enum is declared in the
java.nio.file
package. Methods supporting this option
let you pass an argument of the
LinkOption
type.
■
the NIO.2 apI also supports regular links (also known as hard links). You can use the
createLink(Path
newLink, Path existingPath)
method of the
Files
class to create a hard link.
Tip
Different Forms of a Path
You can get different type of representations for a path. Suppose you create a
Path
object as follows:
// Create a Path object to represent a relative path
Path p1 = Paths.get("test.txt");
Here,
p1
is a relative path. You can get the absolute path that is represented by
p1
using its
toAbsolutePath()
method as follows:
// Get the absolute path represented by p1
Path p1AbsPath = p1.toAbsolutePath();
Now the
p1AbsPath
is the absolute path for
p1
. For example, on Windows,
p1AbsPath
may look like
C:\testapp\
test.txt
. If a path is not an absolute path, the
toAbsolutePath()
method uses a platform-dependent default
directory to resolve the path to give you the absolute path. If the path is an absolute path, the
toAbsolutePath()
method returns the same path.