Implement rm -rf in Java.

I had a chance to implement the process of recursively deleting the directory, that is, the process equivalent to rm -rf in Java, so I will leave a note (´ ・ ω ・ `) Not limited to this process Files.walkTree is useful if you want to process directories recursively. Files.walkTree easily implements recursive processing by giving the path of the directory to be processed as the first argument and FileVisitor which defines the behavior when a file or directory is detected as the second argument. can.

Now, FileVisitor is an interface that requires the implementation of four methods, but if you inherit the SimpleFileVisitor class, you can easily achieve the purpose by simply overriding the required methods. For example, you can create a FileVisitor that recursively traverses a directory and deletes all files and directories as follows:

import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

public class RemoveRecurseFileVisitor extends SimpleFileVisitor<Path> {
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        return delete(file);
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
        return delete(dir);
    private FileVisitResult delete(Path path) {
        try {
            System.out.printf("removed '%s'%n", path);
            return FileVisitResult.CONTINUE;
        } catch (IOException e) {
            throw new UncheckedIOException(e);

Now let's actually move the created code. First, execute the following series of commands in order.

mkdir -p dir01/dir02/dir03
touch dir01/file1
touch dir01/dir02/file2
touch dir01/dir02/file3
touch dir01/dir02/dir03/file4
touch dir01/dir02/dir03/file5
touch dir01/dir02/dir03/file6

This should create a directory file similar to the following:

$ find dir1/ -exec stat -c '%n (%F)' {} \;
dir1/ (directory)
dir1/dir2 (directory)
dir1/dir2/dir3 (directory)
dir1/dir2/dir3/txt4 (regular empty file)
dir1/dir2/dir3/txt5 (regular empty file)
dir1/dir2/dir3/txt6 (regular empty file)
dir1/dir2/txt2 (regular empty file)
dir1/dir2/txt3 (regular empty file)
dir1/txt1 (regular empty file)

Now use RemoveRecurseFileVisitor to create to remove dir1 and the files and directories under it.

import java.nio.file.Files;
import java.nio.file.Paths;

public class Main {
    public static void main(String[] args) throws IOException {
        var target = Paths.get("dir1");
        Files.walkFileTree(target, new RemoveRecurseFileVisitor());

After that, if you compile and execute this, you should be able to confirm that the deletion log is output to the standard output first (´ ・ ω ・ `)

removed 'dir1\dir2\dir3\txt4'
removed 'dir1\dir2\dir3\txt5'
removed 'dir1\dir2\dir3\txt6'
removed 'dir1\dir2\dir3'
removed 'dir1\dir2\txt2'
removed 'dir1\dir2\txt3'
removed 'dir1\dir2'
removed 'dir1\txt1'
removed 'dir1'

You can confirm that the directory dir1 and everything under it have been deleted with a command like the following.

$ ls -l dir1
ls: cannot access 'dir1': No such file or directory


Recommended Posts

Implement rm -rf in Java.
Implement two-step verification in Java
Implement Basic authentication in Java
Implement math combinations in Java
2 Implement simple parsing in Java
Implement Email Sending in Java
Implement XML signature in Java
3 Implement a simple interpreter in Java
Implement reCAPTCHA v3 in Java / Spring
Implement PHP implode function in Java
Try to implement Yubaba in Java
1 Implement simple lexical analysis in Java
How to implement date calculation in Java
How to implement Kalman filter in Java
Implement API Gateway Lambda Authorizer in Java Lambda
Partization in Java
Try to implement n-ary addition in Java
Changes in Java 11
Rock-paper-scissors in Java
How to implement coding conventions in Java
Implement something like a stack in Java
Pi in Java
FizzBuzz in Java
I tried to implement deep learning in Java
[java] sort in list
Read JSON in Java
Interpreter implementation in Java
Make Blackjack in Java
Rock-paper-scissors app in Java
NVL-ish guy in Java
Combine arrays in Java
"Hello World" in Java
Callable Interface in Java
Comments in Java source
Azure functions in java
Format XML in Java
Boyer-Moore implementation in Java
Hello World in Java
Use OpenCV in Java
webApi memorandum in java
Type determination in Java
Ping commands in Java
Various threads in java
Heapsort implementation (in java)
Zabbix API in Java
ASCII art in Java
Compare Lists in Java
Express failure in Java
Implement CustomView in code
Create JSON in Java
Date manipulation in Java 8
What's new in Java 8
Use PreparedStatement in Java
What's new in Java 9,10,11
Parallel execution in Java
Initializing HashMap in Java
Implement markdown in Rails
I tried to implement Firebase push notification in Java
Quickly implement a singleton with an enum in Java
Summary of how to implement default arguments in Java