YouTip LogoYouTip

Java Nio File List

Java File Java java.nio.file.Files\n
\n

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

\n

Method Definition

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

Method Parameters

\n

dir Parameter

\n
    \n
  • Type: java.nio.file.Path
  • \n
  • Description: The path to the directory whose contents are to be listed
  • \n
  • Notes:\n
      \n
    • If the argument is not a directory, a NotDirectoryException will be thrown
    • \n
    • The path must exist, otherwise a NoSuchFileException will be thrown
    • \n
    • If the program lacks read permissions for the directory, an AccessDeniedException will be thrown
    • \n
    \n
  • \n
\n
\n

Return Value

\n

Stream

\n
    \n
  • Description: A stream containing all entries (files and subdirectories) in the directory
  • \n
  • Characteristics:\n
      \n
    • Elements in the stream are Path objects
    • \n
    • The stream is ordered according to the natural order of entries in the directory (typically sorted by name)
    • \n
    • The stream is lazily loaded; directory contents are only actually read when iterated
    • \n
    • The stream must be properly closed to release system resources
    • \n
    \n
  • \n
\n
\n

Method Features

\n

1. Non-recursive

\n

The list() method only lists entries directly located in the specified directory and does not recursively list contents within subdirectories.

\n

2. Excludes Special Entries

\n

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

\n

3. Resource Management

\n

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

\n

Example

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

Usage Examples

\n

Basic Usage: List Directory Contents

\n

Example

\n
import java.io.IOException;\n\nimport java.nio.file.Files;\n\nimport java.nio.file.Path;\n\nimport java.nio.file.Paths;\n\nimport java.util.stream.Stream;\n\npublic class ListDirectoryExample {\n\npublic static void main(String[] args){\n\n Path dir = Paths.get("C:/example");\n\ntry(Stream<Path> stream = Files.list(dir)){\n\n stream.forEach(System.out::println);\n\n}catch(IOException e){\n\n e.printStackTrace();\n\n}\n\n}\n\n}
\n

Advanced Usage: Filter Specific Files

\n

Example

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

Converting to Other Collections

\n

Example

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

Exception Handling

\n

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

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

Performance Considerations

\n
    \n
  1. Lazy Loading: Streams are lazily loaded, meaning the directory is only actually read when a terminal operation (such as forEach) is executed
  2. \n
  3. Resource Consumption: For directories containing a large number of files, using streams avoids loading all entries into memory at once
  4. \n
  5. Parallel Processing: You can call the parallel() method to enable parallel processing, but be mindful of thread safety issues
  6. \n
\n
\n

Comparison with Similar Methods

\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
MethodReturn TypeRecursiveIncludes Special EntriesNotes
Files.list()Stream<Path>NoNoRecommended, resource-friendly
File.listFiles()File[]NoNoTraditional IO method
Files.walk()Stream<Path>YesYesRecursively lists all contents
Files.newDirectoryStream()DirectoryStream<Path>NoNoRequires manual closing
\n
\n

Best Practices

\n
    \n
  1. Always use try-with-resources: Ensure the stream is properly closed
  2. \n
  3. Handle Exceptions: Properly handle potential IOExceptions
  4. \n
  5. Consider Using Filters: Filter out unwanted entries early in stream operations
  6. \n
  7. Avoid Modifying Directories: Do not modify directory contents while iterating over them
  8. \n
  9. Be Aware of Symbolic Links: By default, symbolic links are followed, which may lead to circular references
  10. \n
\n
\n

Summary

\n

The Files.list() method is a modern approach to handling directory contents in Java NIO. It provides all the advantages of the Stream API, including lazy execution, chained operations, and parallel processing capabilities. For simple directory listing requirements, it is more flexible and efficient than the traditional File.listFiles() method.

\nJava File Java java.nio.file.Files
← Java Nio File CreatedirectoryJava Nio File Lines β†’