在 Java 中检测符号链接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2490351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detecting a symlink in Java
提问by Matt Sheppard
Given a Java 'File' object, how can I detect whether or not it refers to a symlink?
给定一个 Java 'File' 对象,我如何检测它是否引用了符号链接?
(If it helps/matters, I know the file refers to a directory, not to a file)
(如果有帮助/重要,我知道该文件指的是目录,而不是文件)
回答by Bozho
File.getCanonicalPath()resolves symlinks
File.getCanonicalPath()解析符号链接
A canonical pathname is both absolute and unique. The precise definition of canonical form is system-dependent. This method first converts this pathname to absolute form if necessary, as if by invoking the getAbsolutePath() method, and then maps it to its unique form in a system-dependent way. This typically involves removing redundant names such as "." and ".." from the pathname, resolving symbolic links (on UNIX platforms), and converting drive letters to a standard case (on Microsoft Windows platforms).
规范路径名既是绝对的又是唯一的。规范形式的精确定义取决于系统。如有必要,此方法首先将此路径名转换为绝对形式,就像调用 getAbsolutePath() 方法一样,然后以依赖于系统的方式将其映射到其唯一形式。这通常涉及删除冗余名称,例如“。” 和路径名中的“..”,解析符号链接(在 UNIX 平台上),并将驱动器号转换为标准大小写(在 Microsoft Windows 平台上)。
I assume you can compare the result of getCanonicalPath()and getAbsolutePath().
我想你可以比较的结果getCanonicalPath()和getAbsolutePath()。
Update: It appears this question has already been asked - check the answers there
更新:似乎已经有人问过这个问题 - 检查那里的答案
回答by Wayne
Also you can use isSymbolicLink(Path path)method. It will be more reliable.
您也可以使用isSymbolicLink(Path path)方法。它会更可靠。
java.io.File file = ...;
boolean isSymbolicLink = Files.isSymbolicLink(file.toPath());
Similar examples from Java Doc 'Detecting a Symbolic Link'.
来自 Java Doc ' Detecting a Symbolic Link' 的类似示例。

