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)
xxxxxxxxxx
1
/C/
2
└── directory/
3
│
4
├── subdirectory1/
5
│
6
└── subdirectory2/
7
│
8
└── file.txt
In this example, we use recursion to delete a non-empty directory, because to delete the directory we need to clear it first.
xxxxxxxxxx
1
import java.io.File;
2
import java.io.IOException;
3
4
5
public class Example {
6
7
public static void main(String[] args) throws IOException {
8
File file = new File("C:\\directory\\subdirectory2");
9
10
deleteDirectoryLegacyIO(file);
11
}
12
13
public static void deleteDirectoryLegacyIO(File file) {
14
File[] listFiles = file.listFiles();
15
if (listFiles != null) {
16
for (File temp : listFiles) {
17
//recursive delete
18
System.out.println("Opened: " + temp);
19
deleteDirectoryLegacyIO(temp);
20
}
21
}
22
23
if (file.delete()) {
24
System.out.printf("Deleted: %s%n", file);
25
} else {
26
System.err.printf("Unable to delete: %s%n", file);
27
}
28
29
}
30
}
Output:
xxxxxxxxxx
1
Opened: C:\directory\subdirectory2\file.txt
2
Deleted: C:\directory\subdirectory2\file.txt
3
Deleted: C:\directory\subdirectory2
In this example, we use Files.walkFileTree
with SimpleFileVisitor
to delete a directory.
xxxxxxxxxx
1
package tmpOperations;
2
3
import java.io.IOException;
4
import java.nio.file.*;
5
import java.nio.file.attribute.BasicFileAttributes;
6
7
8
public class Example {
9
10
public static void main(String[] args) throws IOException {
11
Path path = Paths.get("C:\\directory\\subdirectory2");
12
13
Files.walkFileTree(path,
14
new SimpleFileVisitor<>() {
15
16
// delete directories
17
18
public FileVisitResult postVisitDirectory(Path directory, IOException exc)
19
throws IOException {
20
Files.delete(directory);
21
System.out.printf("Deleted directory: %s%n", directory);
22
return FileVisitResult.CONTINUE;
23
}
24
25
// delete files
26
27
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
28
throws IOException {
29
Files.delete(file);
30
System.out.printf("Deleted file: %s%n", file);
31
return FileVisitResult.CONTINUE;
32
}
33
}
34
);
35
}
36
}
Output:
xxxxxxxxxx
1
Deleted file: C:\directory\subdirectory2\file.txt
2
Deleted directory: C:\directory\subdirectory2