In Java, we can use the Files.walk()
API to traverse all files from a folder and its subfolders.
Table of contents:
- 1. Traverse all files from a folder in Java
- 2. Traverse all files from a folder and its subfolders in Java
- 3. List all file name from a folder in Java
- 4. Find a file from a folder and its subfolders in Java
- 5. Download Source Code
- 6. References
P.S Tested with Java 21
1. Traverse all files from a folder in Java
Let’s assume the folder /Users/mkyong/projects/test/
contains the following files:
|-- a.txt
|-- b.txt
|-- bootstrap-icons.min.css
|-- example.tar.gz
The following example uses Files.walk()
API to traverse all files’ and directories’s paths from a folder, filter it to include only the files Files::isRegularFile
and print out the file path.
package com.mkyong.io.howto;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class FileTraverseExample {
public static void main(String[] args) {
// Specify the directory we want to traverse
String dirPath = "/Users/yongmookkim/projects/test/";
// Traverse the directory and process files
try (Stream<Path> paths = Files.walk(Paths.get(dirPath))) {
paths
.filter(Files::isRegularFile) // ensure it is a file
.forEach(System.out::println); // prints the file path
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Output
/Users/mkyong/projects/test/example.tar.gz
/Users/mkyong/projects/test/bootstrap-icons.min.css
/Users/mkyong/projects/test/b.txt
/Users/mkyong/projects/test/a.txt
Note
Files.walk()
: This method returns a Stream<Path>
that is a stream of paths representing the files and directories. The stream will traverse the directory tree in a depth-first manner.
2. Traverse all files from a folder and its subfolders in Java
It works the same; the Files.walk()
API also traverses all files from a folder and its subfolders.
|-- a.txt
|-- b.txt
|-- bootstrap-icons.min.css
|-- example.tar.gz
|-- folderA
| |-- c.txt
| \-- folderB
| \-- d.txt
// Specify the directory we want to traverse
String dirPath = "/Users/yongmookkim/projects/test/";
// Traverse the directory and process files
try (Stream<Path> paths = Files.walk(Paths.get(dirPath))) {
paths
.filter(Files::isRegularFile) // ensure it is a file
.forEach(System.out::println); // prints the file path
} catch (IOException e) {
throw new RuntimeException(e);
}
Output
/Users/mkyong/projects/test/example.tar.gz
/Users/mkyong/projects/test/bootstrap-icons.min.css
/Users/mkyong/projects/test/b.txt
/Users/mkyong/projects/test/a.txt
/Users/mkyong/projects/test/folderA/folderB/d.txt
/Users/mkyong/projects/test/folderA/c.txt
3. List all file name from a folder in Java
The following example uses the Files.walk()
API to traverse and collect all the file names from a folder and its subfolders. In the final step, the program will print out the total number of files collected and all the filenames.
package com.mkyong.io.howto;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Stream;
public class FileTraverseExample2 {
public static void main(String[] args) {
List<String> result;
// Specify the directory we want to traverse
String dirPath = "/Users/yongmookkim/projects/test/";
// Traverse the directory and process files
try (Stream<Path> paths = Files.walk(Paths.get(dirPath))) {
result = paths
.filter(Files::isRegularFile) // ensure it is a file
.map(p -> p.getFileName().toString())
.toList();
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println("Total files: " + result.size());
for (String name : result) {
System.out.println("FileName: " + name);
}
}
}
Output
Total files: 5
FileName: example.tar.gz
FileName: bootstrap-icons.min.css
FileName: b.txt
FileName: a.txt
FileName: d.txt
FileName: c.txt
4. Find a file from a folder and its subfolders in Java
The following example uses the Files.walk()
API to find a specific file name a.txt
from a folder and its subfolders.
package com.mkyong.io.howto;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.stream.Stream;
public class FileTraverseExample3 {
public static void main(String[] args) {
String dir = "/Users/yongmookkim/projects/test/";
String findThisFile = "a.txt";
try {
Optional<Path> foundFile = findFileByName(Paths.get(dir), findThisFile);
foundFile.ifPresentOrElse(
file -> System.out.println("File found: " + file),
() -> System.out.println("File not found.")
);
} catch (IOException e) {
System.err.println("An error occurred while searching for the file: " + e.getMessage());
}
}
public static Optional<Path> findFileByName(Path directory, String fileName) throws IOException {
try (Stream<Path> stream = Files.walk(directory)) {
return stream
.filter(Files::isRegularFile)
.filter(path -> path.getFileName().toString().equals(fileName))
.findFirst();
}
}
}
Output
/Users/mkyong/projects/test/a.txt
5. Download Source Code
$ git clone https://github.com/mkyong/core-java
$ cd java-io
6. References
- Oracle – Walking the File Tree
- Java Files.walk examples
- How to get size of a directory in Java
- How to read a file in Java
- Java – How to list all files in a directory
The post How to traverse all files from a folder in Java appeared first on Mkyong.com.