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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 26, 2024 (edit link).