EN
Java - delete directory
0
points
In this article, we would like to show you how to delete a directory in Java.
Below we describe several ways on how to delete a directory:
- Recursively,
Files.walkFileTree
(Java 7)
Project structure
/C/
└── directory/
│
├── subdirectory1/
│
└── subdirectory2/
│
└── file.txt
1. Recursively
In this example, we use recursion to delete a non-empty directory, because to delete the directory we need to clear it first.
import java.io.File;
import java.io.IOException;
public class Example {
public static void main(String[] args) throws IOException {
File file = new File("C:\\directory\\subdirectory2");
deleteDirectoryLegacyIO(file);
}
public static void deleteDirectoryLegacyIO(File file) {
File[] listFiles = file.listFiles();
if (listFiles != null) {
for (File temp : listFiles) {
//recursive delete
System.out.println("Opened: " + temp);
deleteDirectoryLegacyIO(temp);
}
}
if (file.delete()) {
System.out.printf("Deleted: %s%n", file);
} else {
System.err.printf("Unable to delete: %s%n", file);
}
}
}
Output:
Opened: C:\directory\subdirectory2\file.txt
Deleted: C:\directory\subdirectory2\file.txt
Deleted: C:\directory\subdirectory2
2. Files.walkFileTree
In this example, we use Files.walkFileTree
with SimpleFileVisitor
to delete a directory.
package tmpOperations;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
public class Example {
public static void main(String[] args) throws IOException {
Path path = Paths.get("C:\\directory\\subdirectory2");
Files.walkFileTree(path,
new SimpleFileVisitor<>() {
// delete directories
@Override
public FileVisitResult postVisitDirectory(Path directory, IOException exc)
throws IOException {
Files.delete(directory);
System.out.printf("Deleted directory: %s%n", directory);
return FileVisitResult.CONTINUE;
}
// delete files
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
Files.delete(file);
System.out.printf("Deleted file: %s%n", file);
return FileVisitResult.CONTINUE;
}
}
);
}
}
Output:
Deleted file: C:\directory\subdirectory2\file.txt
Deleted directory: C:\directory\subdirectory2