Java java.nio.file.Files list() Method
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
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 throw
NotDirectoryException - The path must exist, otherwise it will throw
NoSuchFileException - If the program does not have read permission for the directory, it will throw
AccessDeniedException
- If the parameter is not a directory, it will throw
Return Value
Stream
- Description: A stream containing all entries (files and subdirectories) in the directory
- Features:
- The elements in the stream are
Pathobjects. - 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
- The elements in the stream are
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
stream.forEach(System.out::println);
}
Usage Examples
Basic Usage: List Directory Contents
Example
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
stream.filter(path -> path.toString().endsWith(".java"))
.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
Converting to Other Collections
Example
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:
- NotDirectoryException- When the path is not a directory
- NoSuchFileException- When the directory does not exist
- SecurityException- When there is no permission to read the directory
- IOException- When other I/O errors occur
Performance Considerations
- Lazy loading: The stream is lazily loaded; the directory is actually read only when a terminal operation (such as forEach) is executed
- Resource consumption: For directories containing a large number of files, using a stream can avoid loading all entries into memory at once
- Parallel processing: You can call the
parallel()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
- Always use try-with-resources: Ensure the stream is properly closed
- Handle exceptions: Properly handle possible IOException
- Consider using filters: Filter out unwanted entries as early as possible in the stream operations
- Avoid modifying the directory: Do not modify its contents while traversing the directory
- 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 java.nio.file.Files