阅读97 返回首页    go 阿里云 go 技术社区[云栖]


java File 判断文件是否为符号链接



最简单的方式,直接使用:

private static boolean isSymbolicLink(File f) throws IOException {
        return !f.getAbsolutePath().equals(f.getCanonicalPath());
    }



如果是普通文件,file.getAbsolutePath()和file.getCanonicalPath()是一样的。

如果是link文件,file.getAbsolutePath()是链接文件的路径;file.getCanonicalPath是实际文件的路径(所指向的文件路径)。


apache 使用的判断方式:

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.

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());
}



最后更新:2017-04-03 16:48:31

  上一篇:go Android gallery实现选中放大的效果
  下一篇:go html中iframe控制父页面刷新