A symbolic link (also known as symlink or soft link) is a special file that serves as a reference to another file. In this Java tutorial, we will learn to create, detect and find targets of the symbolic links using examples.
It is worth noting Java NIO classes (such as Path) are link-aware. Its methods provide configurable options enabling us to configure the behavior when a symbolic link is encountered in place of a regular file.
This also means that for most CRUD operations, actions on symbolic links are automatically redirected to the target of the link.
1. Creating Symbolic Links
The Files.createSymbolicLink(link, target)
method is used to create a symlink of the file. It takes two arguments i.e. path to the original file and the destination path where the symlink will be created.
Note that if the target is a relative path then file system operations on the resulting link are relative to the path of the link.
- We can pass the optional FileAttribute constants to tweak the behavior of the created link.
- The method throws FileAlreadyExistsException if a file with the name already exists.
- An UnsupportedOperationException will be thrown if underlying JVM does not support symbolic links.
- In other cases, if an error occur while creating the links then IOException will be thrown.
- We may also encounter SecurityException or FileSystemException if there is any write access permission issue.
Path regularFile = Paths.get("data.txt");
Path link = Paths.get("data_link.txt");
if (Files.exists(link)) {
Files.delete(link);
}
Files.createSymbolicLink(link, regularFile);
2. Checking Synbolic Links
To check if the given file is a symbolic link or not, we can use Files.isSymbolicLink() method.
The isSymbolicLink() method returns:
true
if the file is a symbolic linkfalse
if the file does not existfalse
is not a symbolic linkfalse
if it cannot be determined if the file is a symbolic link or not
boolean isLink = Files.isSymbolicLink(link);
3. Finding the Target of a Link
We can find the path of the target file of a symbolic link by using the readSymbolicLink(link) method.
This method throws NotLinkException if the specified path is not a symbolic link.
try {
Path file = Files.readSymbolicLink(link);
} catch (IOException x) {
System.err.println(x);
}
4. Conclusion
In this tutorial, we learned the Java NIO APIs that support the symbolic links and certain operations on them.
Remember that symbolic links depend on a lot of other factors such as OS support, underlying JVM support, underlying FileStore support etc. If there is any kind of support issue or read-write permissions then relevant exceptions will be thrown.
Happy Learning !!