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

来源:互联网 发布:windows文件系统结构 编辑:程序博客网 时间:2024/05/16 00:24

转自:http://blog.csdn.net/a1129963143/article/details/9255449

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

[java] view plaincopy
  1. private static boolean isSymbolicLink(File f) throws IOException {  
  2.     return !f.getAbsolutePath().equals(f.getCanonicalPath());  
  3. }  

如果是普通文件,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.

[java] view plaincopy
  1. public static boolean isSymlink(File file) throws IOException {  
  2.   if (file == null)  
  3.     throw new NullPointerException("File must not be null");  
  4.   File canon;  
  5.   if (file.getParent() == null) {  
  6.     canon = file;  
  7.   } else {  
  8.     File canonDir = file.getParentFile().getCanonicalFile();  
  9.     canon = new File(canonDir, file.getName());  
  10.   }  
  11.   return !canon.getCanonicalFile().equals(canon.getAbsoluteFile());  
  12. }
0 0
原创粉丝点击