Resolving Directory Symlink in Java

10,826

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().

Share:
10,826
mailmindlin
Author by

mailmindlin

I like OOP, and TPPI (technicpack).

Updated on June 25, 2022

Comments

  • mailmindlin
    mailmindlin almost 2 years

    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?