1. Introduction
In this tutorial, we’ll explore how to recursively list files and directories in Java, a crucial task for projects like file management systems and backup utilities.
Java offers several methods for this purpose, including the traditional java.io and java.nio libraries, as well as external libraries like Apache Commons IO. Each method caters to specific needs and project scales.
We’ll start with the File class from Java IO, then explore the more modern Files.walk() method from Java NIO, and finally discuss the simplifying features of Apache Commons IO for advanced use cases
2. Java IO
The File class in Java’s java.io package offers a straightforward, if somewhat verbose approach, to list directories recursively.
Let’s see a basic example:
static void listFilesJavaIO(File dir) {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
listFilesJavaIO(file);
} else {
LOGGER.info("File: " + file.getAbsolutePath());
}
}
}
This method uses dir.listFiles() to get an array of File objects. It recursively processes directories (file.isDirectory()) and prints the absolute paths of regular files.
3. Java NIO
Java NIO provides the Files.walk() method in the java.nio.file package as a more advanced solution. Files.walk() is an elegant and powerful approach that offers better performance and flexibility through its use of streams.
Let’s see another example:
static void listFilesJavaNIO(Path dir) {
try (Stream<Path> stream = Files.walk(dir)) {
stream.filter(Files::isRegularFile).forEach(path -> LOGGER.info("File: " + path.toAbsolutePath()));
} catch (IOException e) {
LOGGER.severe(e.getMessage());
}
}
This method uses Files.walk(dir) to create a Stream
4. Apache Commons IO
For simplicity and power, we can use Apache Commons IO’s FileUtils.iterateFiles() method. It offers a straightforward way to iterate over all files in a directory and its subdirectories:
static void listFilesCommonsIO(File dir) {
Iterator<File> fileIterator = FileUtils.iterateFiles(dir, null, true);
while (fileIterator.hasNext()) {
File file = fileIterator.next();
LOGGER.info("File: " + file.getAbsolutePath());
}
}
This method uses Apache Commons IO’s FileUtils.iterateFiles() to create an iterator over all files in a directory, then prints each file’s absolute path. Additionally, second parameter of this method allows us to filter files by its extension (e.g: {“java”, “xml”}). In this case it is defaulted to null, so no files are filtered out. And with the last parameter we can easily decide if we want this iteration to be recursive for all subdirectories.
5. Conclusion
In this article, we learned how to recursively list files and directories in Java using multiple techniques.
For legacy support and straightforward setups, java.io might be preferable. It offers a simpler and more familiar approach, especially for projects that do not require advanced functionality.
However, for applications requiring increased performance and modern practices, java.nio is strongly recommended. It provides better performance and more efficient resource management compared to java.io.
If the project’s complexity justifies an external library for simplification, Apache Commons IO is an excellent choice. This library offers robust capabilities and ease of use, making it ideal for more complex or extensive file management tasks.
An example of implementation and all the code snippets in this article can be found over on GitHub.