Java - How to recursively list all files and subdirectories in a directory with examples
This code tip shows how to use Java NIO API to recursively list all sub-directories and files in a given directory.
The directory structure iterated in the below example is -
OUTPUT of the above code
Explanation of the code
The directory structure iterated in the below example is -
C:\JavaBrahman\Level1
which has the structure, shown using the DOS command - DIR /s /b
- C:\JavaBrahman\Level1>DIR /s /b C:\JavaBrahman\Level1\file1.txt C:\JavaBrahman\Level1\file2.txt C:\JavaBrahman\Level1\Level2 C:\JavaBrahman\Level1\Level2\file3.txt C:\JavaBrahman\Level1\Level2\file4.txt
Java code to recursively iterate over a directory
package com.javabrahman.corejava;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.FileVisitor;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.FileVisitResult;
import java.nio.file.FileSystems;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
public class RecursiveFileVisitor {
public static void main(String args[]) {
FileVisitor<Path> simpleFileVisitor = new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir,BasicFileAttributes attrs)
throws IOException {
System.out.println("-------------------------------------");
System.out.println("DIRECTORY NAME:"+ dir.getFileName()
+ "LOCATION:"+ dir.toFile().getPath());
System.out.println("-------------------------------------");
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path visitedFile,BasicFileAttributes fileAttributes)
throws IOException {
System.out.println("FILE NAME: "+ visitedFile.getFileName());
return FileVisitResult.CONTINUE;
}
};
FileSystem fileSystem = FileSystems.getDefault();
Path rootPath = fileSystem.getPath("C:\\JavaBrahman\\LEVEL1");
try {
Files.walkFileTree(rootPath, simpleFileVisitor);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
--------------------------------------- DIRECTORY NAME: LEVEL1 LOCATION: C:\JavaBrahman\LEVEL1 --------------------------------------- FILE NAME: file1.txt FILE NAME: file2.txt --------------------------------------- DIRECTORY NAME: Level2 LOCATION: C:\JavaBrahman\LEVEL1\Level2 --------------------------------------- FILE NAME: file3.txt FILE NAME: file4.txt
- To read through, or walk, through a file tree of a system,
NIO
libraries have provided theFiles.walkFileTree()
static method. The most basic version of this method takes 2 inputs - a startingPath
and aFileVisitor
. - The starting
Path
has to be an instance ofjava.nio.file.Path
interface. java.nio.file.FileVisitor
is also an interface whose most commonly used implementation has been provided by the JDK and is known asSimpleFileVisitor
. An implementation ofSimpleFileVisitor
as an anonymous inner class has been created which overrides two methods -preVisitDirectory()
andvisitFile()
. The anonymous inner class implementation is named -simpleFileVisitor
(note the camel casing for object names).- As the
NIO API
walks the file tree, these two methods are the hooks which let us process events. WhilepreVisitDirectory()
method is invoked when a directory is to be visited next, andvisitFile()
method is invoked when a file is actually visited. - The
NIO API
uses visitor patternClick to read detailed tutorial on Visitor Design Pattern to walk through the files. DIRECTORY NAME
andDIRECTORY LOCATION
is printed for each directory visited while theFILE NAME
is printed for each visited file.- To invoke the
Files.walkFileTree()
method, first an instance ofFileSystem
is obtained fromFileSystems.getDefault()
method.FileSystems
is a factoryClick to read detailed tutorial on Factory Design Pattern of file systems and thegetDefault()
method returns a handle to the default file system on which the system is running. - Then from the
fileSystem
instance we create the aPath
instance, namedrootPath
, with the path"C:\\JavaBrahman\\LEVEL1"
. - Lastly, we invoke the
Files.walkFileTree()
method with therootPath
object and thesimpleFileVisitor
object.