Resolving Directory Symlink in Java
Asked Answered
S

1

13

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?

Stilla answered 6/2, 2015 at 18:4 Comment(2)
So why doesn't Files.isSymbolicLink not working? What operating system are you on? Works fine for me on Linux, anyway.Shame
"None of them seem to work" <-- that is pretty vague. java.nio.file just works in this case. Please show your code.Noddle
N
27

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

Noddle answered 6/2, 2015 at 18:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.