Java 1.6 - 确定符号链接 [英] Java 1.6 - determine symbolic links
问题描述
在 DirectoryWalker 类中,我想确定 File 实例是否实际上是指向目录的符号链接(假设 walker 在 UNIX 系统上运行).鉴于,我已经知道该实例是一个目录,以下是否是确定符号链接的可靠条件?
In a DirectoryWalker class I want to find out if a File instance is actually a symbolic link to a directory (assuming, the walker walks on UNIX systems). Given, I already know the instance is a directory, would the following be a reliable condition to determine the symbolic link?
File file;
// ...
if (file.getAbsolutePath().equals(file.getCanonicalPath())) {
// real directory ---> do normal stuff
}
else {
// possible symbolic link ---> do link stuff
}
推荐答案
Apache Commons 中使用的技术使用父目录的规范路径,而不是文件本身.我认为您不能保证不匹配是由符号链接引起的,但这很好地表明文件需要特殊处理.
The technique used in Apache Commons uses the canonical path to the parent directory, not the file itself. I don't think that you can guarantee that a mismatch is due to a symbolic link, but it's a good indication that the file needs special treatment.
This is Apache code (subject to their license), modified for compactness.
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 - 确定符号链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!