Table of Content
How to list all files in a directory in Java
Say we want to get names of all the files under a directory and its subdirectories.
Basically, we need to be able to look under each subdirectory and, if it has any files, add them to the result.
This is a problem that can be solved recursively.
In the following section, we have two different methods doing the same thing.
Example 1 creates a
File
object with the given path and iterates over its contents.
If the content is a file, we add it to the return list.
Example 1: Get Files
public List getFiles(String path) {
List result = new ArrayList<>();
File root = new File(path);
File[] filesAndDirectories = root.listFiles();
if (filesAndDirectories != null) {
for (var file : filesAndDirectories) {
if (file.isFile()) {
result.add(file.getName());
} else if (file.isDirectory()) {
List subResult = getFiles(file.getPath());
result.addAll(subResult);
}
}
}
return result;
}
In the second example, we are creating a
Stream
from the given path.
Using functional programming (lambdas), we filter all the files from the stream and collect the file names in the returned list.
We are using Files::isRegularFile
method reference to invoke the static method isRegularFile
.
Example 2: Get All Files Using Files.walk
public List getFiles(String path) throws IOException {
Stream walk = Files.walk(Paths.get(path));
List result = walk
.filter(Files::isRegularFile)
.map(x -> x.getFileName().toString())
.collect(Collectors.toList());
result.forEach(System.out::println);
walk.close();
return result;
}
No comments :
Post a Comment
Please leave your message queries or suggetions.
Note: Only a member of this blog may post a comment.