Java 1.6 - 确定符号链接 [英] Java 1.6 - determine symbolic links

查看:28
本文介绍了Java 1.6 - 确定符号链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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.

这是Apache 代码(根据他们的许可),修改为紧凑性.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆