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

Java File Java java.nio.file.Files


java.nio.file.Files.list()is a utility method provided in the Java NIO (New I/O) package for listing the contents of a directory. This method returns aStream<Path>object, containing all entries (files and subdirectories) in the specified directory.

Method Definition

public static Stream<Path> list(Path dir) throws IOException

Method Parameters

dir parameter

  • Type:java.nio.file.Path
  • Description: The directory path whose contents are to be listed
  • Notes:
    • If the parameter is not a directory, it will throwNotDirectoryException
    • The path must exist, otherwise it will throwNoSuchFileException
    • If the program does not have read permission for the directory, it will throwAccessDeniedException

Return Value

Stream

  • Description: A stream containing all entries (files and subdirectories) in the directory
  • Features:
    • The elements in the stream arePathobjects.
    • The stream is ordered by the natural order of the entries in the directory (usually sorted by name)
    • The stream is lazily loaded; it actually reads the directory contents only when traversed
    • The stream must be properly closed to release system resources

Method Features

1. Non-recursive

list()The method only lists entries directly in the specified directory; it does not recursively list the contents of subdirectories.

2. Excludes special entries

The returned stream does not contain the entries for the directory itself (".") and the parent directory ("..").

3. Resource Management

Since a Stream is returned, it is recommended to use a try-with-resources statement to ensure the stream is properly closed:

Example

try (Stream<Path> stream = Files.list(Paths.get("/path/to/dir"))) {
    stream.forEach(System.out::println);
}

Usage Examples

Basic Usage: List Directory Contents

Example

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class ListDirectoryExample {
    public static void main(String[] args) {
        Path dir = Paths.get("C:/example");
       
        try (Stream<Path> stream = Files.list(dir)) {
            stream.forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Advanced Usage: Filtering Specific Files

Example

try (Stream<Path> stream = Files.list(Paths.get("/projects"))) {
    stream.filter(path -> path.toString().endsWith(".java"))
          .forEach(System.out::println);
} catch (IOException e) {
    e.printStackTrace();
}

Converting to Other Collections

Example

try (Stream<Path> stream = Files.list(Paths.get("/images"))) {
    List<Path> imageFiles = stream.collect(Collectors.toList());
    // Process the collected file list
} catch (IOException e) {
    e.printStackTrace();
}

Exception Handling

Files.list()The method may throw the following exceptions:

  1. NotDirectoryException- When the path is not a directory
  2. NoSuchFileException- When the directory does not exist
  3. SecurityException- When there is no permission to read the directory
  4. IOException- When other I/O errors occur

Performance Considerations

  1. Lazy loading: The stream is lazily loaded; the directory is actually read only when a terminal operation (such as forEach) is executed
  2. Resource consumption: For directories containing a large number of files, using a stream can avoid loading all entries into memory at once
  3. Parallel processing: You can call theparallel()method to implement parallel processing, but note thread safety issues

Comparison with Similar Methods

Method Return Type Recursiveness Contains Special Entries Remarks
Files.list() Stream<Path> no no Recommended, resource-friendly
File.listFiles() File[] no no Traditional IO method
Files.walk() Stream<Path> Yes Yes Recursively lists all contents
Files.newDirectoryStream() DirectoryStream<Path> no no Needs to be manually closed

Best Practices

  1. Always use try-with-resources: Ensure the stream is properly closed
  2. Handle exceptions: Properly handle possible IOException
  3. Consider using filters: Filter out unwanted entries as early as possible in the stream operations
  4. Avoid modifying the directory: Do not modify its contents while traversing the directory
  5. Be aware of symbolic links: By default, symbolic links are followed, which may cause circular references

Summary

Files.list()The method is a modern way to handle directory contents in Java NIO, providing all the advantages of the Stream API, including lazy execution, chained operations, and parallel processing capabilities. For simple directory listing needs, it is more flexible and efficient than traditionalFile.listFiles()methods.

Java File Java java.nio.file.Files

Other Extensions