Java File.list and listFiles
List immediate names or obtain File objects to inspect each entry.
A simple example
File.list and listFiles
- Start with One folder containing a.txt and b.txt
- Do this List and sort its names
- Result a.txt, b.txt
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.javaPick 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.
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);
}
}
}
}
[A.csv, B.csv] 3
Filtering by suffix selects two names. The object-based filter also includes the text note.
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.
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);
}
}
}
}
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.
What to watch for
The order is unspecified. These methods may return null if the target is not a readable directory.