Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java java.nio.file.Files newDirectoryStream() Method

Java java.nio.file.Files newDirectoryStream() Method

Java File Java java.nio.file.Files


java.nio.file.Files.newDirectoryStream() is a very practical method in the Java NIO (New I/O) package for traversing files and subdirectories in a directory. Compared with the traditional java.io.File , it provides a more efficient and flexible way to traverse directories.

Method Definition

public

static

DirectoryStream

<

Path

newDirectoryStream

(

Path dir

)

throws

IOException

public

static

DirectoryStream

<

Path

newDirectoryStream

(

Path dir,

String

glob

)

throws

IOException

public

static

DirectoryStream

<

Path

newDirectoryStream

(

Path dir, DirectoryStream.

Filter

filter ) throws IOException ### Parameter Description #### 1. Basic Form Parameters - `dir` (Path type): The directory path to open - Return value: `DirectoryStream`, representing an iteration stream of all entries in the directory #### 2. Filtered Form Parameters - `glob` (String type): A glob pattern used to match file names - `filter` (DirectoryStream.Filter type): Custom filter interface --- ## Usage Examples ### 1. Basic Usage: Traversing a Directory ## Example import java.io.IOException ; import java.nio.file.* ; import java.nio.file.attribute.BasicFileAttributes ; public class DirectoryStreamExample {     public static void main ( String [ ] args ) {         Path dir = Paths. get ( "C:/example" ) ;                 try ( DirectoryStream < Path > stream = Files. newDirectoryStream ( dir ) ) {             for ( Path file : stream ) {                 System . out . println ( file. getFileName ( ) ) ;             }         } catch ( IOException e ) {             e. printStackTrace ( ) ;         }     } } ### 2. Filtering with a Glob Pattern ## Example // List only .txt files try ( DirectoryStream < Path > stream = Files. newDirectoryStream ( dir, "*.txt" ) ) {     for ( Path file : stream ) {                 System . out . println ( file. getFileName ( ) ) ;     } } ### 3. Using a Custom Filter ## Example // List only directories DirectoryStream. Filter < Path > filter = new DirectoryStream. Filter < Path > ( ) {     @Override     public boolean accept ( Path entry ) throws IOException {         return Files. isDirectory ( entry ) ;     } } ; try ( DirectoryStream < Path > stream = Files. newDirectoryStream ( dir, filter ) ) {     for ( Path file : stream ) {                 System . out . println ( file. getFileName ( ) ) ;     } } } --- ## Method Characteristics ### 1. Efficiency - Uses NIO's channel features, more efficient than the traditional `File.listFiles()` - Especially suitable for directories containing a large number of files ### 2. Resource Management - The returned `DirectoryStream` implements the `AutoCloseable` interface - It is recommended to use the try-with-resources statement to ensure resources are released correctly ### 3. Thread Safety - Not thread-safe and cannot be shared among multiple threads - If concurrent processing is needed, an independent stream should be created for each thread --- ## Notes 1. **IO Exception Handling**: You must handle or declare `IOException` 2. **Resource Release**: You must close the stream to avoid resource leaks 3. **Performance Considerations**: For very large directories, you may need to consider batch processing 4. **Symbolic Links**: Follows symbolic links by default unless specially configured --- ## Alternative Comparison | Method | Advantages | Disadvantages | | --- | --- | --- | | `Files.newDirectoryStream()` | Efficient, supports filtering | Not thread-safe | | `Files.list()` (Java 8+) | Returns a Stream, supports parallel processing | Requires Java 8+ | | `File.listFiles()` | Simple and easy to use | Lower performance | --- ## Best Practices 1. Always use the try-with-resources statement 2. For complex filtering logic, use a custom filter 3. Consider batch processing when handling large directories 4. In a Java 8+ environment, `Files.list()` may be a better choice --- ## FAQ ### Q1: How to handle hidden files? You can use a custom filter: ## Example DirectoryStream. Filter < Path > filter = entry -> ! entry. getFileName ( ) . toString ( ) . startsWith ( "." ) ; ### Q2: How to recursively traverse subdirectories? `newDirectoryStream()` itself is not recursive; you can combine it with `Files.walkFileTree()` to achieve recursive traversal. ### Q3: What are the performance optimization suggestions? - Avoid expensive operations in the filter - For read-only operations, consider using `Files.list()` and parallel streams Through this detailed explanation, you should have mastered the core usage and best practices of the `Files.newDirectoryStream()` method. This method is a very practical tool in Java file operations, and using it reasonably can significantly improve directory traversal efficiency. [![Java File](https://www.runoob.com/images/up.gif) Java java.nio.file.Files ](/java/java-nio-file.html)