NewDirectoryStream. How can we loop over all the files from a folder? In Java, we can use the Files class and call Files.newDirectoryStream, and then use a for-loop.
With this method, we need to get a Path representing the target directory. Then, we need to wrap the method call in an exception-handling block, as it might cause an error.
import java.io.*;
import java.nio.file.*;
public class Program {
public static void main(String[] args) {
// Step 1: get path to a folder.
var path = FileSystems.getDefault().getPath("programs");
// Step 2: call Files.newDirectoryStream to get paths from a folder.
try (var stream = Files.newDirectoryStream(path)) {
// Step 3: enumerate the paths in a for-loop and print them out.
for (Path entry : stream) {
System.out.println("Path: " + entry);
}
} catch (IOException exception) {
// Step 4: if an error occurred, handle it.
System.err.println("Error");
}
}
}Path: programs/program.go
Path: programs/example.txt
Path: programs/Program.java
Path: programs/program.py
Path: programs/program.scala
Path: programs/program.swift
Path: programs/program.php
Path: programs/program.js
Summary. With the Path and DirectoryStream types, we can access all the paths in a folder in an elegant way. Occasionally an exception may occur if the directory is missing.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 26, 2024 (edit link).