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

Code Factory
2 min readJul 2, 2020

--

Donate : Link

WordPress Blog : Link

Learn how to delete a directory recursively along with all its subdirectories and files.

Delete directory recursively — Java 8+

This example makes use of Files.walk(Path) method that returns a Stream<Path> populated with Path objects by walking the file-tree in depth-first order.

project_folder > folders > folder1 > folder1.1 > test.txt

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

Output :

Deleting: folders\folder1\folder1.1\test.txt
Deleting: folders\folder1\folder1.1
Deleting: folders\folder1
Deleting: folders

Delete directory recursively — Java 7

The following example uses Files.walkFileTree(Path, FileVisitor) method that traverses a file tree and invokes the supplied FileVisitor for each file.

We use a SimpleFileVisitor to perform the delete operation.

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

Output :

Deleting file: folders\folder1\folder1.1\test.txt
Deleting dir: folders\folder1\folder1.1
Deleting dir: folders\folder1
Deleting dir: folders

--

--

No responses yet