Java — How to delete a directory recursively with all its subdirectories and files | Code Factory

Delete directory recursively — Java 8+

package com.example.java.programming.file;import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;
/**
* @author code.factory
*
*/
public class DeleteDirectoryRecursively {
public static void main(String... args) throws IOException {
Path dir = Paths.get("folders");
// Traverse the file tree in depth-first fashion and delete each file/directory.
Files.walk(dir).sorted(Comparator.reverseOrder()).forEach(path -> {
try {
System.out.println("Deleting: " + path);
Files.delete(path);
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
Deleting: folders\folder1\folder1.1\test.txt
Deleting: folders\folder1\folder1.1
Deleting: folders\folder1
Deleting: folders

Delete directory recursively — Java 7

package com.example.java.programming.file;import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
/**
* @author code.factory
*
*/
public class DeleteDirectoryRecursively1 {
public static void main(String... args) throws IOException {
Path dir = Paths.get("folders");
// Traverse the file tree and delete each file/directory.
Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
System.out.println("Deleting file: " + file);
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
System.out.println("Deleting dir: " + dir);
if (exc == null) {
Files.delete(dir);
return FileVisitResult.CONTINUE;
} else {
throw exc;
}
}
});
}
}
Deleting file: folders\folder1\folder1.1\test.txt
Deleting dir: folders\folder1\folder1.1
Deleting dir: folders\folder1
Deleting dir: folders

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Quick fixes for analysis issues

Generics in Swift

Space Arrays (SPACEARR) Solution — Codechef March Long Challenge

A Day in the Life of the Dialexa Software Team

Ruby Algorithm Questions For Beginners

Machine Learning, Linear Regression, and Crypto Trading

Comparing the Top Low-Code Platforms of 2022

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Code Factory

Code Factory

More from Medium

Ski boot debugging

Access modifiers in java

Filtering requests for a specific controller or set of methods with Spring MVC

Main Components of JVM