In this tutorial, I am going to show you how to read all files in a folder using Java 8 walk syntax.
Java 8 How to Read all files in a folder:
Java 7 introduced Files class that consists exclusively of static methods that operate on files, directories, or other types of data.
From Java 8 Walk method was introduced as part of Files class which is used to read the files under the specified path or directory.
Java 8 Walk takes three parameters :
start– The starting file.
maxDepth – The maximum number of directory levels to visit.
Options – options to configure the traversal.
And returns Stream of Path (Stream<Path>) it contains all available files under given start point.
Java 8 Walk Example:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class Java8ReadFiles {
public static void main(String[] args) {
try (Stream < Path > paths = Files.walk(Paths.get("C:\\DemoFolder"))) {
paths
.filter(Files::isRegularFile)
.forEach(System.out::println);
} catch (Exception e) {
e.printStackTrace();
}
}
}
It will print all regular files under the given start point. On the above example, we have used Java 7’s most valuable feature try with the resource it is also called as Automatic Resource Management.
Legacy Style to read all files in a folder :
import java.io.File;
public class Java8ReadFiles {
public static void main(String[] args) {
try {
final File folder = new File("C:\\DemoFolder");
listAllFiles(folder);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void listAllFiles(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listAllFiles(fileEntry);
} else {
System.out.println(fileEntry.getName());
}
}
}
}
Reference:
Happy Learning 🙂