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.
This program imports the required Java IO classes with 2 import statements at the top. This is necessary to more easily access the types.
getPath
with a folder name on the default file system. This accesses a "programs" folder in the working directory.Files.newDirectoryStream
, and pass the Path
object we created. This returns a DirectoryStream
.for
-loop over the Path
instances in the DirectoryStream
, and print each one to System.out
.Files.newDirectoryStream
to throw an exception, so we may want to handle that here.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
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.