转自:http://blog.csdn.net/a1129963143/article/details/9255449
最简单的方式,直接使用:
- 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());
- }