Java 7+: Deleting Recursively A Directory

Path directory = Paths.get("/tmp");
   Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
	   public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
		   return FileVisitResult.CONTINUE;

	   public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
		   return FileVisitResult.CONTINUE;


NEW online workshop: WebStandards Igniter (online)

Airport MUC workshops: Java EE 7: Bootstrap, Effective, Architectures, Web, React and Angular, Testing and Microservices

Podcast: and newsletter:

A book about rethinking Java EE Patterns


Is this pro or con Java 7+? This task should be a one liner. Same as reading the file content to a String. I have no idea why this is still not possible in plain Java SE.

Posted by Franz van Betteraey on February 25, 2014 at 08:34 AM CET #

How about this one liner:
FileUtils.deleteDirectory(path.toFile()); ?
Commons IO does a good job here, otherwhise you will have to encapsulate that code using FileVisitor.

Posted by Nestor on March 01, 2014 at 01:27 AM CET #

"How about this one liner:
FileUtils.deleteDirectory(path.toFile()); ?"

That's not a one liner. It is one line of code and one dependency. I am sure the FileUtils.deleteDirectory() method implementation is not one line of code. It should be.

Posted by jim on September 01, 2014 at 04:11 PM CEST #

Jim, you're wrong if you think that things like 'deleteDirectory' should be always one plain liner, with no more implementation, just like a black box.

In order to be a good programmer you must to know the basics, and in this respect: basic Java IO: copying files using streams, then you can move to abstract that repeated code to a method that you can reuse many times.

That last part is what Commons IO have done for you, instead that you write your own code that you must test and mantain, you have a proven library with many reusable methods.

Of course that every dependency should be clearly justified for one project.

Posted by Nestor on September 05, 2014 at 02:39 PM CEST #

Why would a real programmer ever want to delete a directory with a one-liner? He must be stupid inexperienced or lazy.

You know this type of programmer must be educated on how to traverse with the Visitor pattern. Only when he writes enough times 10 lines of code instead of one line, only then he will be master.

Just kidding. It's another one of those practical things where the Java API designers didn't bother to add. Perhaps it wasn't enterprise enough..

Posted by SPIDERMAN on January 15, 2015 at 05:36 PM CET #

Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
...the last 150 posts
...the last 10 comments