Google Guava: Delete all files in a directory (now deprecated)

The class can delete a file but not a collection of files or a whole directory including its containing files. declares two methods to do this job:

  • static void deleteDirectoryContents(File directory)
    Delete all the files within a directory but not the directory itself. If the contents of this or any subdirectory can’t be listed an IOException("Error listing files for " + directory) will be thrown.
  • static void deleteRecursively(File file) throws IOException
    Delete a file or directory and all contents recursively. This methods calls deleteDirectoryContents() first and then file.delete(). If this directory can’t be deleted an IOException("Failed to delete " + file) will be thrown.

Because a file can be a symbolic link it is important to understand the semantics of these methods. If a containing file or directory is a symbolic link will the symbolic link itself be deleted or will the method follow the link and delete the target? None of the methods follow symbolic links because it’s simply not possible with the JDK. If these methods find a symbolic link then just the link will be deleted. But what if the methods are called on a directory which is itself a symbolic link?

If deleteDirectoryContents() is called on a File object which is a symbolic link to a directory nothing will happen at all because as already mentioned symbolic links are not followed; so deleteDirectoryContents() will not delete the directory the method was called on. If on the other site deleteRecursively() is called on a symbolic link then just the symbolic link to this directory is deleted but not the target directory itself. That’s just how symbolic links works in Java and has nothing to do with the actual deleteXXX()-methods.


Alternative: Use NIO.2 from Java 7 or copy the old source code to your project.

Ähnliche Beiträge

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht.