Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolving Directory Symlink in Java

Tags:

java

symlink

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?

like image 891
mailmindlin Avatar asked Feb 06 '15 18:02

mailmindlin


People also ask

How do I find a symlink in 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.

What is symlinks in Java?

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.

How do I remove a link in Java?

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.

Can you symlink directories?

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.


1 Answers

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

like image 120
fge Avatar answered Sep 18 '22 17:09

fge