Java File list() Method

Java File Java File


File.list()is in Javajava.io.Filean instance method provided by the class, used to obtain the list of names of all files and subdirectories in the specified directory.

Method Syntax

public String[] list()

Method Return Value

list()The method returns a string array (String[]), which contains the following:

  • If the calling object represents a valid directory, returns the names of all files and subdirectories under that directory
  • If the calling object does not represent a directory or an I/O error occurs, returnsnull
  • If the directory is empty, returns an empty array

Basic Usage Example

Example

import java.io.File;

public class ListFilesExample {
    public static void main(String[] args) {
        // Create a File object representing a directory
        File directory = new File("C:/MyFolder");
       
        // Get the list of files and subdirectories in the directory
        String[] files = directory.list();
       
        // Check whether the list was successfully obtained
        if (files != null) {
            System.out.println("Directory contents:");
            for (String file : files) {
                System.out.println(file);
            }
        } else {
            System.out.println("The specified path is not a directory or an error occurred");
        }
    }
}

Method Overload Version

FileThe class also provides another version of thelist()method, which can accept a filter:

Example

public String[] list(FilenameFilter filter)

FilenameFilter Interface

FilenameFilteris a functional interface that contains only one method:

Example

boolean accept(File dir, String name)

Example Using a Filter

Example

import java.io.File;
import java.io.FilenameFilter;

public class FilteredListExample {
    public static void main(String[] args) {
        File directory = new File("C:/MyFolder");
       
        // Only list .txt files
        String[] textFiles = directory.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".txt");
            }
        });
       
        // Java 8+ can use Lambda expressions as shorthand
        String[] textFiles = directory.list((dir, name) -> name.endsWith(".txt"));
       
        if (textFiles != null) {
            System.out.println("Text file list:");
            for (String file : textFiles) {
                System.out.println(file);
            }
        }
    }
}

Notes

  1. Permission issues: If the program does not have permission to read the directory,list()the method will returnnull
  2. Symbolic links:list()The method follows symbolic links and may return the actual file/directory names pointed to by the links
  3. Performance considerations: For a directory containing a large number of files,list()the method may consume more memory
  4. Relative paths: The returned file names only include the name part, not the full path

Alternative Methods

In Java 7 and above, it is recommended to useFilesclasses andDirectoryStreamto handle directory contents, as they provide a more modern and flexible way:

Example

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class NioListExample {
    public static void main(String[] args) throws IOException {
        Path dir = Paths.get("C:/MyFolder");
       
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
            for (Path file : stream) {
                System.out.println(file.getFileName());
            }
        }
    }
}

Summary

File.list()The method is a simple and direct way to get directory contents, suitable for simple file system operations. For more complex needs, consider usingFilenameFilteror turn to the more powerful features provided by the NIO.2 API.

Java File Java File

Other Extensions