header

Torsten Curdt’s weblog

Java File Links

Unfortunately dealing with links and permissions is not really easily possible in java. At least with the following code you can figure out whether you dealing with a link or not. A similar piece code has recently been contributed to the commons-io project. Found that really useful and worth sharing.


public static boolean isLink( final File file ) throws IOException {
        if (file == null || !file.exists()) {
                return false;
        }

        return !file.getCanonicalFile().equals(file.getAbsoluteFile());
}

  • @Attila: Good catch! Thanks!
  • This doesn't seem right. This function will also return true for a non-symlink file, if at least one of the directories in its path is symlinked.

    This should work though:

    File canonicalDir = file.getParentFile().getCanonicalFile();
    File fileInCanonicalDir = new File(canonicalDir, file.getName());
    return fileInCanonicalDir.getCanonicalFile().equals(fileInCanonicalDir.getAbsoluteFile());

    Attila.
  • Steve Loughran
    ...something like this is marked as @since1.5 in the ant codebase. Its known to play up a bit on OS/X
blog comments powered by Disqus