[Java] Processes all files under a certain directory

It's nothing new, but I'll post it somehow.

Files # walkFileTree () added in Java7 seems to be good for processing like the subject.

WalkFileTreeSample.java


import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.io.*;
 
public class WalkFileTreeSample {
    public static void main(String[] args) throws IOException {
        Path start = Paths.get("/Users/daiki/go");
 
        Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
                    System.out.println(file);
                    return FileVisitResult.CONTINUE;
                }
            });
    }
}

SimpleFileVisitor is an ordinary class, not a functional interface, so you can't use lambda expressions. In the above, only the method called for each file is overridden, but there are other methods called before visiting the directory, methods called after, etc., and processing can be sandwiched by overriding.

As another example, you can use Files # walk (), which was added in Java 8. This uses the Stream API. The directory is excluded to match the result with the above. Is it a little uncomfortable?

WalkSample.java


import java.io.IOException;
import java.nio.file.*;
import java.util.stream.Stream;

public class WalkSample {
    public static void main(String[] args) throws IOException {
        Path start = Paths.get("/path/to/target");
        try(Stream<Path> paths = Files.walk(start)) {
            paths.filter(path -> !Files.isDirectory(path))
                .forEach(System.out::println);
        }
    }
}

If it's Java6 or earlier, would you have to write it yourself using recursion? If you just want to output the file name, it's not particularly difficult.

WalkWithoutLibrarySample.java


import java.io.File;

public class WalkWithoutLibrarySample {
    public static void main(String[] args) {
        File start = new File("/path/to/target");
        walk(start);
    }

    private static void walk(File dir) {
        for(File file : dir.listFiles()) {
            if(file.isFile()) {
                System.out.println(file);
            } else {
                walk(file);
            }
        }
    }
}

reference

Recommended Posts

[Java] Processes all files under a certain directory
Use java1.7 (zulu7) under a specific directory with jenv
I want to recursively search for files under a specific directory
[java tool] A tool that deletes files under the specified path by extension
How to save a file with the specified extension under the directory specified in Java to the list
java directory creation