gpt4 book ai didi

Java 1.6 - 确定符号链接(symbolic link)

转载 作者:行者123 更新时间:2023-12-01 04:57:54 25 4
gpt4 key购买 nike

在 DirectoryWalker 类中,我想查明 File 实例是否实际上是目录的符号链接(symbolic link)(假设 walker 在 UNIX 系统上行走)。鉴于我已经知道该实例是一个目录,以下是确定符号链接(symbolic link)的可靠条件吗?

File file;
// ...
if (file.getAbsolutePath().equals(file.getCanonicalPath())) {
// real directory ---> do normal stuff
}
else {
// possible symbolic link ---> do link stuff
}

最佳答案

Apache Commons 中使用的技术使用父目录的规范路径,而不是文件本身。我认为您不能保证不匹配是由于符号链接(symbolic link)造成的,但这很好地表明该文件需要特殊处理。

这是Apache code (受 their license 的约束),为了紧凑性进行了修改。

public static boolean isSymlink(File file) throws IOException {
if (file == null)
throw new NullPointerException("File must not be null");
File canon;
if (file.getParent() == null) {
canon = file;
} else {
File canonDir = file.getParentFile().getCanonicalFile();
canon = new File(canonDir, file.getName());
}
return !canon.getCanonicalFile().equals(canon.getAbsoluteFile());
}

关于Java 1.6 - 确定符号链接(symbolic link),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13800937/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com