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