Explain Codes LogoExplain Codes Logo

Delete all files in directory (but not directory) - one liner solution

java
file-system
exception-handling
file-deletion
Anton ShumikhinbyAnton Shumikhin·Jan 12, 2025
TLDR

Use Java's Files.walk together with a lambda function to clear a directory while keeping the directory intact. Replace "dir_path" with your actual directory path and run this chunk of code:

Files.walk(Path.of("dir_path")).filter(Files::isRegularFile).forEach(p -> { try { Files.delete(p); } catch (IOException e) { // Oopsies happens. Handle the error here. } });

Advanced scenarios and how to handle them

Life isn't always as simple as our fast answer. Here are a few more complex situations you might encounter and how to effectively deal with them in your code.

Handling exceptions like a pro

In the wild world of file systems,read-only files can pop up. So can file-system locks that keep you from deleting a file or directory. Proper handling of these exceptions is imperative:

try (Stream<Path> paths = Files.walk(Path.of("dir_path"))) { paths.filter(Files::isRegularFile).forEach(p -> { try { Files.delete(p); } catch (IOException e) { // Be strong, handle this issue yourself or let the user know. Your choice. } }); } catch (IOException e) { // Here be dragons! Handle the stream opening exception }

The tale of the symlinked directories

If a directory contains symbolic links, the Files.walk method will gallantly follow these links to their destination. To keep things local, use the Files.walk overload with a FileVisitOption:

Files.walk(Path.of("dir_path"), FileVisitOption.FOLLOW_LINKS) .filter(Files::isRegularFile) .forEach(p -> { try { Files.delete(p); } catch (IOException e) { // When life gives you errors, make error-handling code } });

To Depend or Not to Depend?

Should your project's simplicity, purity, and size have a higher priority than ease, consider the native Files API. For those who prefer to work smarter, not harder, the FileUtils.cleanDirectory() from Apache Commons IO is ready to serve.

When to use external libraries

Sometimes you just can't avoid external dependencies. Here, let FileUtils.cleanDirectory() do the heavy lifting for nested directories:

FileUtils.cleanDirectory(new File("dir_path")); // The Apache Commons IO at your service, milord

Remember, exceptions are the party poopers here. cleanDirectory() throws an IllegalArgumentException if the directory does not exist and an IOException if cleaning fails. Prep your cleanup code with appropriate exception handling.

Java 8 - A functional style solution

Want to keep things fashionable and functional? Use Files.newDirectoryStream for a cleaner, streamlined process:

Files.newDirectoryStream(Path.of("dir_path"), Files::isRegularFile) .forEach(p -> { try { Files.delete(p); } catch (IOException e) { // Like my momma always said: "Exceptions are like bugs, they're everywhere." } });

Safe and sound file deletion

Always consider safety and efficacy when crafting deletion logic. Here's a handy list of tips:

  • Verify permissions and ownership. Your code must respect private property.
  • Consider Files.deleteIfExists() to avoid the NoSuchFileException monster.
  • Utilize Files.walkFileTree for greater control, this is especially handy when applying filters or handling special cases.

Maintain predictability across various environments to ensure your one-liner behaves consistently everywhere.