Deleting symbolic links via the java.nio.file.Path API

fm fudmail at gmail.com
Sun Oct 3 23:23:23 PDT 2010


Something seems odd to me about the fact that the two following code
snippets do not behave the same for symbolic links:

    if (somePath.exists()) { somePath.delete(); }

and

    somePath.deleteIfExists();

Assume somePath is a java.nio.file.Path and represents a symbolic link
on the file system.

If somePath points to a nonexistent file on the file system (i.e., it
is a broken symbolic link), then the first snippet of code will fail
to call somePath.delete(). Therefore the broken symbolic link remains
on the file system.  However, the second snippet of code always
results in the removal of the symbolic link from the filesystem
(broken link or not).

The difference is that exists() in the first snippet checks the
existence of the symbolic link's target file and not the symbolic link
file itself; The notion of exists in the second snippet applies to the
symbolic link and not its target.

Anyone have thoughts about this particular behavior of the exists()
method? Should the exists() method behavior be more explicit by adding
a LinkOption... paramenter? This would enable the call a call like

    somePath.exists(LinkOption.NOFOLLOW_LINK)

to check the existence of the link itself (if somePath happens to be a
symbolic link) and not the link's target.

Regards.


More information about the nio-dev mailing list