Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read the path that a broken symbolic link points to?

Tags:

java

If symlink is a File object that corresponds to a symbolic link, then:

File target = symlink.getCanonicalPath();

… succeeds in returning the target that it is pointing to. Paths#toRealPath() also works in the same situation.

However, if the symbolic link is broken (dangling), both of the above APIs fail to return a File (or Path) representing the (non-existing) thing that it's pointing to.

I am writing a tool that needs to be able to read those values, even for dangling symlinks. What API do I use to obtain the file or directory that a symlink points at (regardless of whether the symlink is correct or broken)?

update

Based on the accepted answer, one can obtain the target of the symlink (even a broken one) using:

Path target = Files.readSymbolicLink(Paths.get("/some/directory/symlink"));

… if target is then relative, you can de-reference it based on the location where the symlink itself is found by doing the following:

Paths.get("/some/directory/symlink").resolveSibling(".").resolve(target);
like image 231
Marcus Junius Brutus Avatar asked Oct 25 '25 03:10

Marcus Junius Brutus


1 Answers

You can use java's nio file system api:

Path target = Files.readSymbolicLink(Paths.get("/symlink"));

Java documentation stipulates that "the target of the link need not exist".

like image 64
sturcotte06 Avatar answered Oct 27 '25 16:10

sturcotte06