snippetjavaCritical
How can I read all files in a folder from Java?
Viewed 0 times
howfromjavafilesfoldercanallread
Problem
How can I read all the files in a folder through Java? It doesn't matter which API.
Solution
Use:
The Files.walk API is available from Java 8.
The example uses the try-with-resources pattern recommended in the API guide. It ensures that no matter circumstances, the stream will be closed.
public void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
}
}
}
final File folder = new File("/home/you/Desktop");
listFilesForFolder(folder);The Files.walk API is available from Java 8.
try (Stream paths = Files.walk(Paths.get("/home/you/Desktop"))) {
paths
.filter(Files::isRegularFile)
.forEach(System.out::println);
}The example uses the try-with-resources pattern recommended in the API guide. It ensures that no matter circumstances, the stream will be closed.
Code Snippets
public void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
}
}
}
final File folder = new File("/home/you/Desktop");
listFilesForFolder(folder);try (Stream<Path> paths = Files.walk(Paths.get("/home/you/Desktop"))) {
paths
.filter(Files::isRegularFile)
.forEach(System.out::println);
}Context
Stack Overflow Q#1844688, score: 1151
Revisions (0)
No revisions yet.