Library contents

Java File.list and listFiles

List immediate names or obtain File objects to inspect each entry.

A simple example

File.list and listFiles

  1. Start with One folder containing a.txt and b.txt
  2. Do this List and sort its names
  3. Result a.txt, b.txt
Listing discovers the entries. Sorting makes their displayed order predictable.

Syntax

Java syntax
public String[] list()
JDK 21 declarations (5)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Pick only invoices for the checkout summary

A folder holds two invoices and an instruction note. The accountant needs the invoice names in a stable order, plus a count of all regular files for a closing checklist.

First output line[A.csv, B.csv]
Main.java
import java.nio.file.*;
import java.io.*;
import java.util.*;

class Main {
    public static void main(String[] args) throws Exception {
        Path desk = Files.createTempDirectory("file-lesson-");
        try {
            Files.createFile(desk.resolve("B.csv"));
            Files.createFile(desk.resolve("A.csv"));
            Files.createFile(desk.resolve("notes.txt"));
            String[] bills = desk.toFile().list((dir, name) -> name.endsWith(".csv"));
            File[] files = desk.toFile().listFiles(File::isFile);
            if (bills == null || files == null) throw new IOException("Cannot list invoices");
            Arrays.sort(bills);
            System.out.println(Arrays.toString(bills));
            System.out.println(files.length);
        } finally {
            try (var paths = Files.walk(desk)) {
                for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
                    Files.deleteIfExists(p);
            }
        }
    }
}
Output
[A.csv, B.csv]
3

Filtering by suffix selects two names. The object-based filter also includes the text note.

Advertisements

Handle an empty folder and a mistaken filename

An intake tool is given either an empty inbox or the name of a single uploaded document. Distinguish these cases so an invalid listing cannot be reported as a successful check with zero submissions.

First output line0
Main.java
import java.nio.file.*;
import java.io.*;

class Main {
    public static void main(String[] args) throws Exception {
        Path desk = Files.createTempDirectory("file-lesson-");
        try {
            String[] empty = desk.toFile().list();
            if (empty == null) throw new IOException("Cannot list inbox");
            System.out.println(empty.length);
            File document = Files.createFile(desk.resolve("essay")).toFile();
            System.out.println(document.list() == null);
        } finally {
            try (var paths = Files.walk(desk)) {
                for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
                    Files.deleteIfExists(p);
            }
        }
    }
}
Output
0
true

An empty directory yields an empty array. A regular file cannot supply a directory listing.

Inventory class submissions

A teacher receives two top-level files and one file in a team folder. Count regular files in the top-level folder only. Do not count subfolders as files.

Givenanna.pdf · li.pdf · team/plan.pdf
Worked result2

What to watch for

The order is unspecified. These methods may return null if the target is not a readable directory.

Documentation for File.list and listFiles