Given a File
or Path
directory object, how do I check if it is a symlink and how do I resolve it to the actual directory?
I've tried File.getCannonicalFile()
, Files.isSymbolicLink(Path)
and many other methods, but none of them seem to work. One interesting thing is that Files.isDirectory(Path)
returns false, while Files.exists(Path)
is true. Is java treating the symlink as a file instead of a directory?
The icon of the folder would have an arrow. The output of ls -l will clearly indicate that the folder is a symbolic link and it will also list the folder where it points to. Here symbolic is a symbolic link pointing to original folder.
A symbolic or soft link is a just link to the original file, whereas a hard link is a mirror copy of the original file. If the original file is removed, the soft link has no value, because it points to a non-existent file. In case of a hard link, if you delete the original file, it is still usable.
delete("path"); The directory needs to be empty. if the Path is a symbolic link, then the link is deleted and not the target that it represents.
A symbolic link, also known as a soft link or symlink, is a special file pointing to another file or directory using an absolute or relative path. Symbolic links are similar to shortcuts in Windows and are useful when you need quick access to files or folders with long paths.
If you want to fully resolve a Path
to point to the actual content, use .toRealPath()
:
final Path realPath = path.toRealPath();
This will resolve all symbolic links etc.
However, since this can fail (for instance, a symlink cannot resolve), you'll have to deal with IOException
here.
Therefore, if you want to test whether a symlink points to an existing directory, you will have to do:
Files.isDirectory(path.toRealPath());
Note a subtlety about Files.exists()
: by default, it follows symbolic links.
Which means that if you have a symbolic link as a path
whose target does not exist, then:
Files.exists(path)
will return FALSE; but this:
Files.exists(path, LinkOption.NOFOLLOW_LINKS)
will return TRUE.
In "Unix parlance", this is the difference between stat()
and lstat()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With