如何读取破坏的符号链接指向的路径?(How to read the path that a broken symbolic link points to?)

编程入门 行业动态 更新时间:2024-10-24 08:30:35
如何读取破坏的符号链接指向的路径?(How to read the path that a broken symbolic link points to?)

如果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".

更多推荐

本文发布于:2023-08-04 09:18:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1414811.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路径   符号   链接   read   path

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!