JavaUsing DirectoryStream in Java

Using DirectoryStream in Java content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Java Developer Tutorials

How to quickly use DirectoryStream in Java

This Java programming tutorial will show developers how to quickly use the DirectoryStream interface to obtain a list of file names of a given type (or types) specified during the newDirectoryStream.

DirectoryStream examples in Java

Below is a code example showing how to use the DirectoryStream interface to gather a list of file name of a certain type in Java:


import java.util.*;
import java.nio.file.*;

public class UsingDirectoryStream
	public static void main(String args[])
		UsingDirectoryStream usingDirectoryStream = new UsingDirectoryStream();
	private void proceed()
		String fileTypes = "*.{java}";
		Path currDir = Paths.get(".");
		List pathResult = new ArrayList<>();

		try (DirectoryStream directoryStream = Files.newDirectoryStream(currDir, fileTypes)) {
			for (Path filePath: directoryStream) {
				System.out.println("Found: " + filePath);
		}catch(DirectoryIteratorException directoryIteratorException) 
			System.out.println("DirectoryIteratorException: " + directoryIteratorException);
		}catch(IOException ioException) 
			System.out.println("IOException: " + ioException);


Running this Java code snippet in your integrated development environment (IDE) or code editor would produce the following expected output:

[root@mypc]# java UsingDirectoryStream
Found: .\
Found: .\
Found: .\
Found: .\
Found: .\

Read: Top Java IDEs

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories