Java 1.6 - determine symbolic links Java 1.6 - determine symbolic links java java

Java 1.6 - determine symbolic links


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.

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 does not provide such low level access to the file system. Looks like NIO 2, which should be included in Java 1.7, will have support for symbolic links. A draft of the new API is available. Symbolic links are mentioned there, creating and following them is possible. I'm not exactly sure that which method should be used to find out whether a file is a symbolic link. There's a mailing list for discussing NIO 2 - maybe they will know.


Also, watch out for file.isFile() and file.isDirectory() both returning results based on the resolved file and therefore both returning false when file refers to a symlink where the target doesn't exist.

(I know this isn't a useful answer in itself but it tripped me up a couple of times so thought I should share)