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.io.*; import java.util.*; import java.nio.file.*; public class UsingDirectoryStream { public static void main(String args[]) { UsingDirectoryStream usingDirectoryStream = new UsingDirectoryStream(); usingDirectoryStream.proceed(); } 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) { pathResult.add(filePath); 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: .\ArrayListVsHashMap.java Found: .\CombiningExceptions.java Found: .\ConvertingToMicroseconds.java Found: .\ConvertToOctal.java Found: .\UsingDirectoryStream.java
Read: Top Java IDEs