Home
Map
Files.newDirectoryStream: Get Files From FolderCall Files.newDirectoryStream with a Path and then loop over all the returned Paths within the folder.
Java
This page was last reviewed on Jan 26, 2024.
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.
Directory Size
Example. This program imports the required Java IO classes with 2 import statements at the top. This is necessary to more easily access the types.
Step 1 We call getPath with a folder name on the default file system. This accesses a "programs" folder in the working directory.
Step 2 We call Files.newDirectoryStream, and pass the Path object we created. This returns a DirectoryStream.
Step 3 We use a for-loop over the Path instances in the DirectoryStream, and print each one to System.out.
Console
Step 4 It is possible for Files.newDirectoryStream to throw an exception, so we may want to handle that here.
try
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).
Home
Changes
© 2007-2024 Sam Allen.