Example of DirectoryStream in Java | java.nio.file API

By Arvind Rai, 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)
 
extPattern can be *.java and for than one extension we can use it like "*.{java,txt,exe}". Find the example below.

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();
		   }
	}
}
 
We have initialized Path and have been passed to Files.newDirectoryStream with the given extension list. It returns DirectoryStream object. Now we can iterate it to get the all the files.
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us