Course contentsShow
← Java
Lesson 2081 of 2,87041. NIO.2 and the Path APIFree lesson

Reading Directory Attributes During Listing

Efficiently checking file attributes (size, modified time, isDirectory) while iterating to avoid repeated I/O calls.

Reading Directory Attributes During Listing

What you'll learn: How to retrieve file attributes like size, modification time, and type during directory traversal without making extra I/O calls.

The Problem: Double I/O Overhead

When listing directory contents, you often need metadata about each file—is it a directory? How big is it? When was it modified? The naive approach calls Files.list() to get paths, then separately queries each path's attributes:

Files.list(directory).forEach(path -> {
    boolean isDir = Files.isDirectory(path);  // I/O call #1
    long size = Files.size(path);             // I/O call #2
    // ... more separate calls
});

This causes multiple disk reads per file, which is slow for large directories.

The Solution: Read Attributes During Traversal

Both DirectoryStream and Files.list() can be enhanced to fetch attributes during iteration, not after. The file system already has this metadata available when listing—you just need to capture it.

Using BasicFileAttributes

try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
    for (Path entry : stream) {
        BasicFileAttributes attrs = Files.readAttributes(
            entry, BasicFileAttributes.class);
        
        System.out.println(entry.getFileName() + ": " +
            attrs.size() + " bytes, " +
            "modified: " + attrs.lastModifiedTime() + ", " +
            "isDir: " + attrs.isDirectory());
    }
}

Even Better: Stream with Attribute Reading

Files.list(directory)
    .map(path -> {
        try {
            return new FileInfo(path, 
                Files.readAttributes(path, BasicFileAttributes.class));
        } catch (IOException e) { /* handle */ }
    })
    .forEach(info -> System.out.println(info));

Key Takeaway: Reading file attributes once during directory iteration (using BasicFileAttributes) is far more efficient than making separate attribute queries for each file—consolidate your I/O operations to minimize disk access.