Delete directories recursively in Java Delete directories recursively in Java java java

Delete directories recursively in Java


You should check out Apache's commons-io. It has a FileUtils class that will do what you want.

FileUtils.deleteDirectory(new File("directory"));


With Java 7, we can finally do this with reliable symlink detection. (I don't consider Apache's commons-io to have reliable symlink detection at this time, as it doesn't handle links on Windows created with mklink.)

For the sake of history, here's a pre-Java 7 answer, which follows symlinks.

void delete(File f) throws IOException {  if (f.isDirectory()) {    for (File c : f.listFiles())      delete(c);  }  if (!f.delete())    throw new FileNotFoundException("Failed to delete file: " + f);}


In Java 7+ you can use Files class. Code is very simple:

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;   }});