Adam Bien's Weblog

Tuesday Feb 25, 2014

Java 7+: Deleting Recursively A Directory


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

	   @Override
	   public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
		   Files.delete(dir);
		   return FileVisitResult.CONTINUE;
	   }

   });


Special Event: Java 8 with Java EE 7: "More Power with Less Code", 13th October, 2014

A book about rethinking Java EE Patterns

Comments:

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 #

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