Library contents

Java Files.list and newDirectoryStream

Enumerate the immediate children of a directory and close the resulting stream.

A simple example

Files.list and newDirectoryStream

  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 static Stream<Path> list(Path dir) throws IOException
JDK 21 declarations (4)
Run these examples in Java

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

java Main.java

Count the reading lists available for a class

A class folder contains two text reading lists and one image. The teacher wants a count of all entries as well as an alphabetical display containing only the reading lists.

First output line3
Main.java
import java.nio.file.*;

class Main {
    public static void main(String[] args) throws Exception {
        Path desk = Files.createTempDirectory("file-lesson-");
        try {
            Files.createFile(desk.resolve("poems.txt"));
            Files.createFile(desk.resolve("map.png"));
            Files.createFile(desk.resolve("essays.txt"));
            try (var entries = Files.list(desk)) { System.out.println(entries.count()); }
            try (var text = Files.newDirectoryStream(desk, "*.txt")) {
                var names = new java.util.ArrayList<String>();
                for (Path p : text) names.add(p.getFileName().toString());
                names.sort(null);
                System.out.println(names);
            }
        } finally {
            try (var paths = Files.walk(desk)) {
                for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
                    Files.deleteIfExists(p);
            }
        }
    }
}
Output
3
[essays.txt, poems.txt]

The directory stream applies the glob to each entry. Sorting makes the result independent of filesystem order.

Advertisements

Recognize a folder without matching invoices

A new market stall has an instruction note in its export folder but no invoices yet. Ask for CSV entries only and verify that a successful empty result is possible.

Resultfalse
Main.java
import java.nio.file.*;

class Main {
    public static void main(String[] args) throws Exception {
        Path desk = Files.createTempDirectory("file-lesson-");
        try {
            Files.createFile(desk.resolve("instructions.txt"));
            try (var bills = Files.newDirectoryStream(desk, "*.csv")) {
                System.out.println(bills.iterator().hasNext());
            }
        } finally {
            try (var paths = Files.walk(desk)) {
                for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
                    Files.deleteIfExists(p);
            }
        }
    }
}
Output
false

The listing succeeds and provides no matching entries.

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

Directory iteration order is unspecified. Sort entries when output needs to be reproducible.

Documentation for Files.list and newDirectoryStream