Example of DirectoryStream in Java | java.nio.file API
November 29, 2013
java.nio.file.DirectoryStream has been introduced in JDK 7 and is the part of NIO 2. DirectoryStream iterates over the files and returns Path instance for every file. DirectoryStream must be closed after iteration otherwise there will be resource leak. We can restrict DirectoryStream to iterate only specific file by providing file extension.
How To instantiate java.nio.file.DirectoryStream | Files.newDirectoryStream in Java
Files.newDirectoryStream() returns DirectoryStream object. The syntax is given below.public static DirectoryStream<Path> newDirectoryStream(Path dir, String extPattern)
DirectoryStreamExample.java
package com.concretepage.io.file; import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class DirectoryStreamExample { public static void main(String[] args) throws IOException{ DirectoryStream<Path> stream = null; try{ Path dir = Paths.get("D:/page"); stream = Files.newDirectoryStream(dir, "*.{java,txt,exe}"); for (Path p: stream) { System.out.println(p.getFileName()); } } catch (IOException ex) { ex.printStackTrace(); }finally{ stream.close(); } } }