Resolving Directory Symlink in Java
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()
.
Comments
-
mailmindlin almost 2 years
Given a
File
orPath
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 thatFiles.isDirectory(Path)
returns false, whileFiles.exists(Path)
is true. Is java treating the symlink as a file instead of a directory?