Delete all files in directory (but not directory) - one liner solution
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:
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:
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
:
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:
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:
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 theNoSuchFileException
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.
Was this article helpful?