Deleting symbolic links via the java.nio.file.Path API
Alan Bateman
Alan.Bateman at oracle.com
Tue Oct 5 07:16:43 PDT 2010
fm wrote:
> 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.
>
It's only the delete and moveTo methods that are specified to not follow
sym links. It's not clear to me that changing the exists method is worth
it. If someone really needs to then they can use readBasicFileAttributes
specifying NOFOLLOW_LINKS. Furthermore, the exists method isn't really
needed in this API as you've no guarantee that the file still exists
when you go to access it (and from a security point of view it is
usually better to remove the window between the check and the access).
-Alan.
More information about the nio-dev
mailing list