Explain Codes LogoExplain Codes Logo

How to delete a folder with files using Java

java
file-handling
directory-deletion
apache-commons-io
Anton ShumikhinbyAnton Shumikhin·Sep 10, 2024
TLDR

The following code snippet immediately shows how to delete a directory and all its contents using Java's NIO package:

import java.nio.file.*; import java.io.IOException; public class DeleteFolder { public static void main(String[] args) { Path directory = Paths.get("/path/to/directory"); // replace with your directory path try { Files.walkFileTree(directory, new SimpleFileVisitor<Path>() { // Visiting file inside folder isn't just for sightseeing; it's deletion time! @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); // When Java says 'Visit', it means 'Delete'. return FileVisitResult.CONTINUE; // Onto the next one, no vacation for us! } // After visiting all tourist spots (files) inside, exterminate the folder itself. @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); // Deletion routine is a 'post-meal' workout for directories. return FileVisitResult.CONTINUE; } }); System.out.println("Directory vacated. Ready for new residents."); } catch (IOException e) { e.printStackTrace(); // Whoops! Deletion failed, print the stack trace. } } }

Caution: This process is final and throws IOException; double-check paths and permissions.

One-liner with Apache Commons

Apache Commons IO library offers a one-liner solution for deleting directories:

org.apache.commons.io.FileUtils.deleteDirectory(new File("/path/to/directory"));

Before deletion, confirm directory's existence as Juni from Spy Kids would.

Recursive deletion: Explained

Here's your walkthrough guide if you ever decide on custom recursive deletion:

  • Use file.listFiles() to understand the directory's contents and tours available.
  • Avoid symbolic links like teenagers avoid family reunions; you might delete beyond your intended location.
  • Once the contents are cleared, apply file.delete() to remove the directory.

File walking: Java NIO Style

When working with Files.walk():

  • Sort files in reverse order, like reading manga, so directories are deleted after their contents.
  • Use try-with-resources because even Java likes being neat and tidy.
  • For a deletion without tears, opt for Files.deleteIfExists().

Quite a quiet deletion

When you want a silent deletion, FileUtils.deleteQuietly() from Apache Commons IO is your buddy:

org.apache.commons.io.FileUtils.deleteQuietly(new File("/path/to/directory"));

Re-establishing the Vacant Land

Sometimes, you might need to recreate a directory post-deletion, say after a Spring cleaning:

File directory = new File("/path/to/directory"); if(directory.exists()) { FileUtils.deleteDirectory(directory); // Evict the old residents boolean isRecreated = directory.mkdir(); // Welcome the new ones System.out.println("Directory " + (isRecreated ? "" : "not ") + "recreated."); // Party or Pity }

Large Directory Handling

Watch out while dealing with massive directories:

Overflow is a no-go

Leverage streaming API Files.walk() with try-with-resources to keep away from memory leaks.

Exceptions aren't always exceptional

Infuse exception handling within your FileVisitResult methods to tackle potential obstacles.

Post-Deletion Recreation

Consider recreating directories post-deletion as seen in the code snippet above.