List and walk folders
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Programs often need to see what is inside a folder: every photo from the fest, every marks file in every semester folder, every log bigger than 1 MB. The Files class gives you each of these as a stream or a loop of Path objects.
Files.list for one folder
Files.list(dir) returns a Stream<Path> with the direct children of one folder: its files and its sub-folders, but not what is inside those sub-folders.
Example 1 · Listing one folder with Files.list
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.List;import java.util.stream.Stream;
public class ListDemo { public static void main(String[] args) throws IOException { Path sem = Files.createDirectories(Path.of("sem5")); Files.writeString(sem.resolve("dbms.pdf"), "notes"); Files.writeString(sem.resolve("os.pdf"), "notes"); Files.writeString(sem.resolve("marks.csv"), "21,88"); Path lab = Files.createDirectories(sem.resolve("lab")); Files.writeString(lab.resolve("prog1.java"), "class Prog1 {}");
try (Stream<Path> children = Files.list(sem)) { List<String> names = children .map(p -> p.getFileName() + (Files.isDirectory(p) ? "/" : "")) .sorted() .toList(); System.out.println(names); }
try (Stream<Path> children = Files.list(sem)) { long pdfs = children.filter(p -> p.getFileName().toString().endsWith(".pdf")).count(); System.out.println("PDF files: " + pdfs); }
Files.delete(lab.resolve("prog1.java")); Files.delete(lab); for (String n : List.of("dbms.pdf", "os.pdf", "marks.csv")) { Files.delete(sem.resolve(n)); } Files.delete(sem); }}[dbms.pdf, lab/, marks.csv, os.pdf] PDF files: 2
What this code does
Files.listgives only the direct children, so the folderlabappears butprog1.javainside it does not. A/is added to folder names to tell them apart.- The names are sorted because the system's own order is not fixed. A stream can be used once, so the second question opens a new one, again in try-with-resources.
The order is whatever the system gives, which differs between Windows, macOS and Linux. Sort the results when order matters. And because the stream keeps the folder open while you read it, always use it inside try-with-resources; the last section explains why.
Glob patterns with newDirectoryStream
A glob is a simple name pattern, the same kind you type in a terminal: *.csv means "any name ending in .csv". Files.newDirectoryStream(dir, glob) returns only the children whose names match.
Example 2 · Filtering a Downloads folder with globs
import java.io.IOException;import java.nio.file.DirectoryStream;import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;import java.util.Collections;import java.util.List;
public class GlobDemo { static void printMatches(Path dir, String glob) throws IOException { List<String> names = new ArrayList<>(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, glob)) { for (Path p : stream) { names.add(p.getFileName().toString()); } } Collections.sort(names); System.out.println(glob + " -> " + names); }
public static void main(String[] args) throws IOException { Path dir = Files.createDirectories(Path.of("downloads")); List<String> files = List.of("report-2024.pdf", "report-2025.pdf", "report-final.pdf", "marks.csv", "notes.txt", "photo.JPG", "setup.exe"); for (String n : files) { Files.createFile(dir.resolve(n)); }
printMatches(dir, "*.{csv,txt}"); printMatches(dir, "report-20??.pdf"); printMatches(dir, "*.[jJ][pP][gG]"); printMatches(dir, "*.zip");
for (String n : files) { Files.delete(dir.resolve(n)); } Files.delete(dir); }}*.{csv,txt} -> [marks.csv, notes.txt]
report-20??.pdf -> [report-2024.pdf, report-2025.pdf]
*.[jJ][pP][gG] -> [photo.JPG]
*.zip -> []What this code does
{csv,txt}gives a choice of endings, and each?stands for exactly one character, soreport-final.pdfdoes not matchreport-20??.pdf.[jJ][pP][gG]matches.jpgin any mix of case on every system. A plain*.jpgwould findphoto.JPGon Windows only. No match simply gives an empty list.
The result is a DirectoryStream<Path>, which you loop over with for-each and close with try-with-resources.
*matches any number of characters inside one name;?matches exactly one character.{csv,txt}matches any one of the choices, so*.{csv,txt}matches both kinds.[0-9]matches one character from a range or list, such as[jJ].- On Windows glob matching ignores case; on macOS and Linux
*.jpgdoes not matchphoto.JPG.
Files.walk with a depth limit
Files.walk(start) returns a Stream<Path> of everything in a folder tree: the start folder itself first, then every file and sub-folder at every level. It goes depth first: it finishes one sub-folder completely before moving to the next.
Example 3 · Walking a tree, with and without a depth limit
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;import java.util.Comparator;import java.util.List;import java.util.stream.Stream;
public class WalkDemo { static Path makeTree() throws IOException { Path root = Files.createDirectories(Path.of("college-demo")); Files.createDirectories(root.resolve("cse/sem1")); Files.createDirectories(root.resolve("cse/sem2")); Files.createDirectories(root.resolve("ece/sem1")); Files.writeString(root.resolve("cse/sem1/marks.csv"), "21,88\n22,91\n23,79"); Files.writeString(root.resolve("cse/sem1/notes.txt"), "Unit 1: Java basics and OOP"); Files.writeString(root.resolve("cse/sem2/marks.csv"), "21,90\n22,85"); Files.writeString(root.resolve("ece/sem1/marks.csv"), "31,77"); Files.writeString(root.resolve("readme.txt"), "College demo"); return root; }
static String show(Path root, Path p) { List<String> names = new ArrayList<>(); for (Path n : root.relativize(p)) { names.add(n.toString()); } String s = String.join("/", names); return s.isEmpty() ? "." : s; }
static void deleteTree(Path root) throws IOException { // deepest first: next lesson try (Stream<Path> s = Files.walk(root)) { for (Path p : s.sorted(Comparator.reverseOrder()).toList()) { Files.delete(p); } } }
public static void main(String[] args) throws IOException { Path root = makeTree();
try (Stream<Path> all = Files.walk(root)) { all.map(p -> show(root, p)).sorted().forEach(System.out::println); }
try (Stream<Path> top = Files.walk(root, 1)) { System.out.println("Depth 1: " + top.map(p -> show(root, p)).sorted().toList()); }
try (Stream<Path> none = Files.walk(root, 0)) { System.out.println("Depth 0 count: " + none.count()); }
deleteTree(root); }}. cse cse/sem1 cse/sem1/marks.csv cse/sem1/notes.txt cse/sem2 cse/sem2/marks.csv ece ece/sem1 ece/sem1/marks.csv readme.txt Depth 1: [., cse, ece, readme.txt] Depth 0 count: 1
What this code does
Files.walkreturns every folder and file in the tree, including the start folder itself (shown as.).showprints each path relative to the start, with/, so the output is the same on every system.- With depth 1 only the start folder and its direct children appear; depth 0 is the start folder alone.
deleteTreecleans up by deleting the deepest paths first, which the next lesson explains.
Example 4 · Total size of every marks file in the tree
import java.io.IOException;import java.nio.file.FileSystems;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.PathMatcher;import java.util.ArrayList;import java.util.Comparator;import java.util.List;import java.util.stream.Stream;
public class CsvTotalDemo { static Path makeTree() throws IOException { Path root = Files.createDirectories(Path.of("college-demo")); Files.createDirectories(root.resolve("cse/sem1")); Files.createDirectories(root.resolve("cse/sem2")); Files.createDirectories(root.resolve("ece/sem1")); Files.writeString(root.resolve("cse/sem1/marks.csv"), "21,88\n22,91\n23,79"); Files.writeString(root.resolve("cse/sem1/notes.txt"), "Unit 1: Java basics and OOP"); Files.writeString(root.resolve("cse/sem2/marks.csv"), "21,90\n22,85"); Files.writeString(root.resolve("ece/sem1/marks.csv"), "31,77"); Files.writeString(root.resolve("readme.txt"), "College demo"); return root; }
static String show(Path root, Path p) { List<String> names = new ArrayList<>(); for (Path n : root.relativize(p)) { names.add(n.toString()); } String s = String.join("/", names); return s.isEmpty() ? "." : s; }
static void deleteTree(Path root) throws IOException { // deepest first: next lesson try (Stream<Path> s = Files.walk(root)) { for (Path p : s.sorted(Comparator.reverseOrder()).toList()) { Files.delete(p); } } }
public static void main(String[] args) throws IOException { Path root = makeTree(); PathMatcher csv = FileSystems.getDefault().getPathMatcher("glob:*.csv");
List<Path> csvFiles; try (Stream<Path> s = Files.walk(root)) { csvFiles = s.filter(Files::isRegularFile) .filter(p -> csv.matches(p.getFileName())) .sorted(Comparator.comparing(p -> show(root, p))) .toList(); }
long total = 0; for (Path p : csvFiles) { long size = Files.size(p); total += size; System.out.println(show(root, p) + " : " + size + " bytes"); } System.out.println(csvFiles.size() + " files, " + total + " bytes in all");
deleteTree(root); }}cse/sem1/marks.csv : 17 bytes cse/sem2/marks.csv : 11 bytes ece/sem1/marks.csv : 5 bytes 3 files, 33 bytes in all
What this code does
- The
PathMatchertests only the file name, because*never crosses a folder separator:glob:*.csvwould not match the whole pathcse/sem1/marks.csv. - The paths are collected inside try-with-resources, so the walk is closed before the loop.
Files.sizethrowsIOException, which is easy to handle in a plain loop but not inside a stream lambda.
Files.walk(start, maxDepth) stops at a depth you choose. Depth 0 is only the start folder, depth 1 adds its direct children, and so on. Walking a huge folder such as a whole drive can take a long time, so limit the depth when you can. To filter by name inside a walk, use a PathMatcher: FileSystems.getDefault().getPathMatcher("glob:*.csv"), and test each file name with matches(p.getFileName()).
Files.find with a condition
Files.find(start, maxDepth, test) walks the tree like walk, but keeps only the paths for which test returns true.
Example 5 · Files.find: big files and recent files
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.attribute.FileTime;import java.time.Instant;import java.util.ArrayList;import java.util.Comparator;import java.util.List;import java.util.stream.Stream;
public class FindDemo { static Path makeTree() throws IOException { Path root = Files.createDirectories(Path.of("college-demo")); Files.createDirectories(root.resolve("cse/sem1")); Files.createDirectories(root.resolve("cse/sem2")); Files.createDirectories(root.resolve("ece/sem1")); Files.writeString(root.resolve("cse/sem1/marks.csv"), "21,88\n22,91\n23,79"); Files.writeString(root.resolve("cse/sem1/notes.txt"), "Unit 1: Java basics and OOP"); Files.writeString(root.resolve("cse/sem2/marks.csv"), "21,90\n22,85"); Files.writeString(root.resolve("ece/sem1/marks.csv"), "31,77"); Files.writeString(root.resolve("readme.txt"), "College demo"); return root; }
static String show(Path root, Path p) { List<String> names = new ArrayList<>(); for (Path n : root.relativize(p)) { names.add(n.toString()); } String s = String.join("/", names); return s.isEmpty() ? "." : s; }
static void deleteTree(Path root) throws IOException { // deepest first: next lesson try (Stream<Path> s = Files.walk(root)) { for (Path p : s.sorted(Comparator.reverseOrder()).toList()) { Files.delete(p); } } }
public static void main(String[] args) throws IOException { Path root = makeTree(); try (Stream<Path> s = Files.walk(root)) { for (Path p : s.filter(Files::isRegularFile).toList()) { Files.setLastModifiedTime(p, FileTime.from(Instant.parse("2025-02-10T09:00:00Z"))); } } Files.setLastModifiedTime(root.resolve("cse/sem2/marks.csv"), FileTime.from(Instant.parse("2025-03-05T09:00:00Z")));
try (Stream<Path> big = Files.find(root, Integer.MAX_VALUE, (p, attrs) -> attrs.isRegularFile() && attrs.size() > 15)) { System.out.println("Over 15 bytes: " + big.map(p -> show(root, p)).sorted().toList()); }
Instant since = Instant.parse("2025-03-01T00:00:00Z"); try (Stream<Path> recent = Files.find(root, Integer.MAX_VALUE, (p, attrs) -> attrs.isRegularFile() && attrs.lastModifiedTime().toInstant().isAfter(since))) { System.out.println("Changed in March: " + recent.map(p -> show(root, p)).toList()); }
try (Stream<Path> shallow = Files.find(root, 1, (p, attrs) -> attrs.isRegularFile())) { System.out.println("Files at depth 1: " + shallow.map(p -> show(root, p)).toList()); }
deleteTree(root); }}Over 15 bytes: [cse/sem1/marks.csv, cse/sem1/notes.txt] Changed in March: [cse/sem2/marks.csv] Files at depth 1: [readme.txt]
What this code does
- The test lambda gets the path and its
BasicFileAttributes, sosize()andlastModifiedTime()need no extra disk call and throw no checked exception. maxDepthworks as inwalk: with depth 1, onlyreadme.txtis a file directly inside the start folder.
The test is a BiPredicate<Path, BasicFileAttributes>: a lambda that gets the path and its attributes, the facts Java already read about it, such as isRegularFile(), size() and lastModifiedTime().
Because the attributes come ready, find saves a separate disk call per file. It is the natural choice for questions like "every file over 1 MB" or "every file changed this week".
Closing these streams with try-with-resources
Files.list, newDirectoryStream, walk and find all hold an open directory handle, a resource the operating system gives your program. A stream that is never closed keeps it until the garbage collector happens to clean up, which may be never.
// Leaks: the stream is never closedlong leaky = Files.list(dir).count();
// Correct: closed when the block ends, even if it throwslong count;try (Stream<Path> s = Files.list(dir)) { count = s.count();}Example 6 · A folder report method that always closes its stream
import java.io.IOException;import java.io.UncheckedIOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;import java.util.Comparator;import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.stream.Collectors;import java.util.stream.Stream;
public class FolderReportDemo { static Path makeTree() throws IOException { Path root = Files.createDirectories(Path.of("college-demo")); Files.createDirectories(root.resolve("cse/sem1")); Files.createDirectories(root.resolve("cse/sem2")); Files.createDirectories(root.resolve("ece/sem1")); Files.writeString(root.resolve("cse/sem1/marks.csv"), "21,88\n22,91\n23,79"); Files.writeString(root.resolve("cse/sem1/notes.txt"), "Unit 1: Java basics and OOP"); Files.writeString(root.resolve("cse/sem2/marks.csv"), "21,90\n22,85"); Files.writeString(root.resolve("ece/sem1/marks.csv"), "31,77"); Files.writeString(root.resolve("readme.txt"), "College demo"); return root; }
static String show(Path root, Path p) { List<String> names = new ArrayList<>(); for (Path n : root.relativize(p)) { names.add(n.toString()); } String s = String.join("/", names); return s.isEmpty() ? "." : s; }
static void deleteTree(Path root) throws IOException { // deepest first: next lesson try (Stream<Path> s = Files.walk(root)) { for (Path p : s.sorted(Comparator.reverseOrder()).toList()) { Files.delete(p); } } }
static String extension(Path p) { String name = p.getFileName().toString(); int dot = name.lastIndexOf('.'); return dot == -1 ? "(none)" : name.substring(dot + 1); }
static Map<String, Long> countByExtension(Path root) throws IOException { try (Stream<Path> s = Files.walk(root)) { return s.filter(Files::isRegularFile) .collect(Collectors.groupingBy(FolderReportDemo::extension, TreeMap::new, Collectors.counting())); } catch (UncheckedIOException e) { throw e.getCause(); } }
public static void main(String[] args) throws IOException { Path root = makeTree(); System.out.println("By extension: " + countByExtension(root));
try { countByExtension(root.resolve("mech")); } catch (IOException e) { System.out.println("Report failed: " + e.getClass().getSimpleName()); }
deleteTree(root); }}By extension: {csv=3, txt=2}
Report failed: NoSuchFileExceptionWhat this code does
- The
returnhappens inside the try-with-resources block, and the stream is still closed before the method returns.groupingBywith aTreeMapkeeps the extensions sorted. - If an error happens while the walk runs, it arrives as
UncheckedIOException; the method unwraps it withgetCause()so callers see a normalIOException. A missing start folder throwsNoSuchFileExceptionstraight away.
Leak enough and you get "Too many open files" on Linux; on Windows the folder can stay locked so it cannot be deleted.
So every one of them goes in a try-with-resources header. Errors found while the stream runs, such as a sub-folder you may not read, arrive as UncheckedIOException, because stream lambdas cannot throw checked exceptions; getCause() gives the real IOException. Files.walk stops at the first such error.
Find the bug
Find the unclosed stream
Select the line that is wrong.
Count the files in a folder without leaking a directory handle.
Round 1 of 3Next step
Check your understanding
11 quick questions