Adam Bien's Weblog

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 workshop: Microservices with Java EE 7 and Java 8, January 26th, 2015, Airport Munich

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 #

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