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)?
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);
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With