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, used to traverse files and subdirectories in a directory. Compared with the traditionaljava.io.Filemethods, it provides a more efficient and flexible directory traversal method.

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<? super Path> filter) throws IOException

Parameter Description

1. Basic formal parameters

  • dir(Path type): The directory path to open
  • Return value:DirectoryStream<Path>, an iteration stream of all entries in the directory

2. Formal parameters with filter

  • glob(String type): A glob pattern used to match file names
  • filter(DirectoryStream.Filter<? super Path> 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 Glob Patterns

Example

// Only list .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

// Only list 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 channel features, compared with traditionalFile.listFiles()more efficient
  • Especially suitable for handling directories with many files

2. Resource Management

  • The returnedDirectoryStreamimplementsAutoCloseableinterface
  • It is recommended to use the try-with-resources statement to ensure resources are released properly

3. Thread Safety

  • Not thread-safe, cannot be shared across multiple threads
  • If concurrent processing is needed, a separate stream should be created for each thread

Notes

  1. IO exception handling: Must handle or declare throwingIOException
  2. Resource release: Must close the stream to avoid resource leaks
  3. Performance considerations: For very large directories, consider batch processing
  4. Symbolic links: By default, symbolic links are followed 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 custom filters
  3. Consider batch processing when handling large directories
  4. In Java 8+ environments,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()It is not recursive by itself; it can be combined withFiles.walkFileTree()to implement recursive traversal.

Q3: What are the performance optimization suggestions?

  • Avoid expensive operations in the filter
  • For read-only operations, consider usingFiles.list()and parallel streams

Through the detailed explanation in this article, you should have masteredFiles.newDirectoryStream()the core usage and best practices of the method. This method is a very practical tool in Java file operations, and proper use can significantly improve the efficiency of directory traversal.

Java File Java java.nio.file.Files

Other Extensions