Java – How to list all files in a directory?
Two Java examples to show you how to list files in a directory :
- For Java 8,
Files.walk
- Before Java 8, create a recursive loop to list all files.
1. Files.walk
1.1 List all files.
try (Stream<Path> walk = Files.walk(Paths.get("C:\\projects"))) {
List<String> result = walk.filter(Files::isRegularFile)
.map(x -> x.toString()).collect(Collectors.toList());
result.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
1.2 List all folders.
try (Stream<Path> walk = Files.walk(Paths.get("C:\\projects"))) {
List<String> result = walk.filter(Files::isDirectory)
.map(x -> x.toString()).collect(Collectors.toList());
result.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
1.3 List all files end with .java
try (Stream<Path> walk = Files.walk(Paths.get("C:\\projects"))) {
List<String> result = walk.map(x -> x.toString())
.filter(f -> f.endsWith(".java")).collect(Collectors.toList());
result.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
1.4 Find a file – HeaderAnalyzer.java
try (Stream<Path> walk = Files.walk(Paths.get("C:\\projects"))) {
List<String> result = walk.map(x -> x.toString())
.filter(f -> f.contains("HeaderAnalyzer.java"))
.collect(Collectors.toList());
result.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
2. Classic
In the old days, we can create a recursive loop to implement the search file function like this :
2.1 List all files end with .java
package com.mkyong.example;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class JavaExample {
public static void main(String[] args) {
final File folder = new File("C:\\projects");
List<String> result = new ArrayList<>();
search(".*\\.java", folder, result);
for (String s : result) {
System.out.println(s);
}
}
public static void search(final String pattern, final File folder, List<String> result) {
for (final File f : folder.listFiles()) {
if (f.isDirectory()) {
search(pattern, f, result);
}
if (f.isFile()) {
if (f.getName().matches(pattern)) {
result.add(f.getAbsolutePath());
}
}
}
}
}
Hi mkyong,
i have a problem with Java.
I used NetBeans 9.0 to create a jar file to scan a folder with xml files.
When run my code (copy from yours code, in this page) from NetBeans, program get all files of folder.
When make this code a jar file and run it, I do not get all files.
I am confused very much.
I hope to your answer.
When I try to execute first option I get this: caused by: java.nio.file.AccessDeniedException: C:\Documents and Settings
means you don’t have the permissions to access that directory. And make sure this directory isn’t possibly empty.
Because “Documents and Settings” contains a “space” between words.
I dont think the spacing is the problem. I guess he needs to write “C:\\Documents and Settings” in path.