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());
}

3 Responses to “Java File Links”

  1. Steve Loughran said, on 28. July 2008 at 10:48

    …something like this is marked as @since1.5 in the ant codebase. Its known to play up a bit on OS/X

  2. Attila Szegedi said, on 28. July 2008 at 12:31

    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.

  3. tcurdt said, on 28. July 2008 at 12:51

    @Attila: Good catch! Thanks!

Leave a Reply

Please copy the string kgslVf to the field below: