Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

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

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

Java File Java java.nio.file.Files


java.nio.file.Files.list() is a practical method provided in the Java NIO (New I/O) package for listing the contents of a directory. The method returns a Stream 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

- If the parameter is not a directory, throws `NotDirectoryException` - The path must exist, otherwise throws `NoSuchFileException` - If the program does not have read permission for the directory, throws `AccessDeniedException`

Return Value

Stream

- The elements in the stream are `Path` objects - The stream is arranged in the natural order of entries in the directory (usually sorted by name) - The stream is lazily loaded; the directory content is only actually read when traversed - The stream must be closed properly to release system resources

Method Characteristics

1. Non-recursiveness

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

2. Does not include special entries

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

3. Resource management

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

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: filter 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

(

)

;

}

Convert 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 only actually read when a terminal operation (such as forEach) is executed
  2. Resource consumption: For directories containing a large number of files, using a stream avoids loading all entries into memory at once
  3. Parallel processing: You can call parallel() method to enable parallel processing, but be careful about thread safety

Comparison with Similar Methods

Method Return Type Recursiveness Includes special entries Notes
Files.list() Stream No No Recommended, resource-friendly
File.listFiles() File[] No No Traditional IO method
Files.walk() Stream Is Is Recursively list all contents
Files.newDirectoryStream() DirectoryStream No No Needs manual closing

Best Practices

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

Summary

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

Java File Java java.nio.file.Files