如果symlink是与符号链接对应的File对象,则:
File target = symlink.getCanonicalPath();...成功返回它指向的目标。 Paths#toRealPath()也适用于相同的情况。
但是,如果符号链接断开(悬空),则上述两个API都无法返回表示它所指向的(不存在的)事物的File (或Path )。
我正在编写一个需要能够读取这些值的工具,即使对于悬空的符号链接也是如此。 我使用什么API来获取符号链接指向的文件或目录(无论符号链接是正确还是损坏)?
更新
根据接受的答案,可以使用以下方法获取符号链接的目标(即使是破坏的符号):
Path target = Files.readSymbolicLink(Paths.get("/some/directory/symlink"));...如果target是相对的,您可以通过执行以下操作,根据找到符号链接本身的位置取消引用它:
Paths.get("/some/directory/symlink").resolveSibling(".").resolve(target);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);最满意答案
你可以使用java的nio文件系统api:
Path target = Files.readSymbolicLink(Paths.get("/symlink"));Java文档规定“链接的目标不需要存在”。
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".
更多推荐
发布评论