Java Directory Handling
Directories in Java
A directory (folder) is a file-system entry that contains other entries — files and further directories — forming a tree. Applications work with directories constantly: creating an upload folder per user, scanning a folder for new import files, finding all source files in a project, copying a site to a backup location, cleaning up old reports.
Java represents a directory with the same Path type as a file. Whether a path is a directory is a property of what exists on disk, checked with Files.isDirectory(path). The java.nio.file.Files class provides all directory operations:
| Task | Method |
|---|---|
| Create one directory / a whole chain | Files.createDirectory(dir) / Files.createDirectories(dir) |
| List direct entries | Files.list(dir), Files.newDirectoryStream(dir[, glob]) |
| Visit a whole tree | Files.walk(dir[, maxDepth]), Files.find(...), Files.walkFileTree(...) |
| Move or rename | Files.move(source, target) |
| Delete | Files.delete(dir) (empty directories only) |
| React to changes | WatchService |
Creating directories is covered in the Create Files lesson and deleting directory trees in the Delete Files lesson; this lesson focuses on listing, walking, copying, moving and watching.
A Sample Project Folder
The examples use a small project structure created by this helper class:
import java.io.IOException;
import java.nio.file.*;
public class Setup {
static void make(Path root) throws IOException {
for (String d : new String[] {"src/main/java/app", "src/main/resources", "src/test/java/app", "docs"}) {
Files.createDirectories(root.resolve(d));
}
Files.writeString(root.resolve("README.md"), "# Shop\n");
Files.writeString(root.resolve("pom.xml"), "<project/>\n");
Files.writeString(root.resolve("src/main/java/app/Main.java"), "class Main {}\n");
Files.writeString(root.resolve("src/main/java/app/Cart.java"), "class Cart {}\n");
Files.writeString(root.resolve("src/main/resources/application.properties"), "port=8080\n");
Files.writeString(root.resolve("src/test/java/app/CartTest.java"), "class CartTest {}\n");
Files.writeString(root.resolve("docs/guide.md"), "Guide\n");
}
}
Compile it together with each example, for example javac Setup.java L1.java and then java L1. Files.createDirectories and Files.writeString both succeed if the folders and files already exist, so the helper can safely run more than once.
Listing a Directory's Entries
import java.io.IOException;
import java.nio.file.*;
import java.util.stream.Stream;
public class L1 {
public static void main(String[] args) throws IOException {
Path root = Path.of("shop");
Setup.make(root);
System.out.println("== Files.list (direct entries) ==");
try (Stream<Path> entries = Files.list(root)) {
entries.sorted().forEach(p -> System.out.println((Files.isDirectory(p) ? "[dir] " : "[file] ") + p.getFileName()));
}
System.out.println("== DirectoryStream with glob *.{md,xml} ==");
try (DirectoryStream<Path> ds = Files.newDirectoryStream(root, "*.{md,xml}")) {
for (Path p : ds) System.out.println(p.getFileName());
}
try (Stream<Path> s = Files.list(root.resolve("README.md"))) {
s.count();
} catch (NotDirectoryException e) {
System.out.println("NotDirectoryException: " + e.getFile());
}
}
}
Output:
== Files.list (direct entries) ==
[file] README.md
[dir] docs
[file] pom.xml
[dir] src
== DirectoryStream with glob *.{md,xml} ==
README.md
pom.xml
NotDirectoryException: shop/README.md
Files.list
- Returns a
Stream<Path>of the directory's direct entries only — not the contents of subdirectories. Each path includes the directory (shop/README.md), so it can be used directly with otherFilesmethods;getFileName()gives just the name. - The order is whatever the file system returns, which differs between operating systems and even between runs. The example calls
sorted()for predictable output.Pathsorting compares names character by character, so uppercaseREADME.mdsorts before lowercase names. - The stream holds an open directory handle, so it must be closed — always use try-with-resources.
- On a regular file, it throws
NotDirectoryException; on a missing path,NoSuchFileException. (CompareFile.listFiles(), which returnsnullfor all of these cases.)
DirectoryStream with a glob
Files.newDirectoryStream(dir, glob) returns an Iterable of entries whose names match a glob pattern, and it must also be closed. It's convenient in for loops and lets the file system do the filtering.
| Glob | Matches |
|---|---|
*.csv | Names ending in .csv |
*.{md,xml} | Names ending in .md or .xml |
report-202?.pdf | ? matches exactly one character |
[abc]* | Names starting with a, b or c |
In a directory stream, * doesn't cross directory boundaries — only names in this directory are matched.
Walking a Directory Tree
import java.io.IOException;
import java.nio.file.*;
import java.util.stream.Stream;
public class L2 {
public static void main(String[] args) throws IOException {
Path root = Path.of("shop");
Setup.make(root);
System.out.println("== walk, depth 2 ==");
try (Stream<Path> s = Files.walk(root, 2)) {
s.sorted().forEach(p -> {
int depth = p.equals(root) ? 0 : root.relativize(p).getNameCount();
System.out.println(" ".repeat(depth) + p.getFileName());
});
}
System.out.println("== all .java files ==");
try (Stream<Path> s = Files.walk(root)) {
s.filter(Files::isRegularFile)
.filter(p -> p.toString().endsWith(".java"))
.map(root::relativize)
.sorted()
.forEach(System.out::println);
}
System.out.println("== find: test sources ==");
try (Stream<Path> s = Files.find(root, Integer.MAX_VALUE,
(p, attrs) -> attrs.isRegularFile() && p.getFileName().toString().endsWith("Test.java"))) {
s.forEach(p -> System.out.println(root.relativize(p)));
}
}
}
Output:
== walk, depth 2 ==
shop
README.md
docs
guide.md
pom.xml
src
main
test
== all .java files ==
src/main/java/app/Cart.java
src/main/java/app/Main.java
src/test/java/app/CartTest.java
== find: test sources ==
src/test/java/app/CartTest.java
Files.walk
Files.walk(root)returns a stream of the root and every entry beneath it, at any depth. It visits a directory before its contents (depth-first).Files.walk(root, maxDepth)limits how deep it goes: depth 0 is the root itself, depth 1 its direct entries, depth 2 their entries. That's whymainandtestappear but not their contents.- The indentation is computed with
root.relativize(p).getNameCount()— how many names the path has below the root. The root itself is handled separately, because relativizing a path to itself gives an empty path. - Combined with stream operations,
walkanswers most "find files in this tree" questions: filter regular files, match a name, andrelativizeagainst the root for readable output.
Files.find
Files.find(root, maxDepth, matcher) works like walk plus filter, but the matcher receives the file's BasicFileAttributes along with the path. The walk has already read those attributes, so checking attrs.isRegularFile(), attrs.size() or attrs.lastModifiedTime() costs nothing extra, whereas calling Files.isRegularFile(p) inside a walk filter asks the file system again for every entry. Use find when filtering by size or date over large trees.
Things to know about walking
- Symbolic links aren't followed unless you pass
FileVisitOption.FOLLOW_LINKS. When following links, the walk detects cycles and throwsFileSystemLoopExceptioninstead of looping forever. - An unreadable directory stops the stream:
walkandfindthrowUncheckedIOException(wrapping, for example,AccessDeniedException) when the stream reaches it. To skip such directories and continue, usewalkFileTreeand overridevisitFileFailed. - Like
list, these streams hold open directory handles and must be closed.
Practical Example: Disk Usage Report with NIO
The File Class lesson built a disk usage report using File.listFiles() and recursion. With Files.walk, the same report needs no recursion, no null checks, and no risk of looping through symbolic links:
import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.stream.*;
public class Usage {
static String extension(Path p) {
String name = p.getFileName().toString();
int dot = name.lastIndexOf('.');
return dot > 0 ? name.substring(dot + 1).toLowerCase() : "(none)";
}
static long size(Path p) {
try {
return Files.size(p);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
static String human(long bytes) {
if (bytes < 1024) return bytes + " B";
if (bytes < 1024 * 1024) return String.format("%.1f KB", bytes / 1024.0);
return String.format("%.1f MB", bytes / (1024.0 * 1024));
}
public static void main(String[] args) throws IOException {
Path site = Path.of("site");
Files.createDirectories(site.resolve("img"));
Files.createDirectories(site.resolve("css"));
Files.write(site.resolve("index.html"), new byte[4_200]);
Files.write(site.resolve("about.html"), new byte[2_900]);
Files.write(site.resolve("css/main.css"), new byte[18_500]);
Files.write(site.resolve("img/hero.JPG"), new byte[1_450_000]);
Files.write(site.resolve("img/logo.png"), new byte[36_000]);
Files.write(site.resolve("LICENSE"), new byte[1_070]);
Map<String, Long> byExt;
try (Stream<Path> files = Files.walk(site)) {
byExt = files.filter(Files::isRegularFile)
.collect(Collectors.groupingBy(Usage::extension, TreeMap::new,
Collectors.summingLong(Usage::size)));
}
long total = byExt.values().stream().mapToLong(Long::longValue).sum();
byExt.forEach((ext, bytes) -> System.out.printf("%-7s %10s%n", ext, human(bytes)));
System.out.printf("%-7s %10s%n", "total", human(total));
}
}
Output (identical to the File-based version):
(none) 1.0 KB
css 18.1 KB
html 6.9 KB
jpg 1.4 MB
png 35.2 KB
total 1.4 MB
How it works:
- Test files are created with
Files.write(path, new byte[n]), which writesnzero bytes — a quick way to make files of an exact size. Files.walk(site)supplies every path in the tree;filter(Files::isRegularFile)keeps only files.groupingBy(extension, TreeMap::new, summingLong(size))groups files by lowercased extension, keeps the groups sorted, and adds up the sizes in each group — the whole aggregation in one collector.sizewrapsIOExceptioninUncheckedIOException, becauseFiles.sizethrows a checked exception and a method reference used in a stream can't (see the Throws Keyword lesson). The original exception remains available as the cause.- Total: the group sums are added together.
Practical Example: Copying a Directory Tree
Files.copy copies a single file; for a directory it creates only an empty directory at the target. Copying a whole tree means creating each directory and copying each file. walkFileTree is a good fit, because its visitor methods are called at exactly the right moments and can skip whole subtrees — here, a project backup that leaves out build output and Git metadata.
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Set;
import java.util.stream.Stream;
public class CopyTree {
static int copyTree(Path source, Path target, Set<String> skipDirs) throws IOException {
int[] copied = {0};
Files.walkFileTree(source, new SimpleFileVisitor<>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
if (!dir.equals(source) && skipDirs.contains(dir.getFileName().toString())) {
return FileVisitResult.SKIP_SUBTREE;
}
Files.createDirectories(target.resolve(source.relativize(dir)));
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.copy(file, target.resolve(source.relativize(file)),
StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
copied[0]++;
return FileVisitResult.CONTINUE;
}
});
return copied[0];
}
public static void main(String[] args) throws IOException {
Path project = Path.of("shop");
Setup.make(project);
Files.createDirectories(project.resolve("target/classes"));
Files.writeString(project.resolve("target/classes/Main.class"), "bytecode");
Files.createDirectories(project.resolve(".git"));
Files.writeString(project.resolve(".git/HEAD"), "ref: refs/heads/main");
Path backup = Path.of("backup", "shop-2026-11-15");
int n = copyTree(project, backup, Set.of("target", ".git"));
System.out.println("copied " + n + " files");
try (Stream<Path> s = Files.walk(backup)) {
s.filter(Files::isRegularFile).map(backup::relativize).sorted().forEach(p -> System.out.println(" " + p));
}
System.out.println("target skipped: " + Files.notExists(backup.resolve("target")));
}
}
Output:
copied 7 files
README.md
docs/guide.md
pom.xml
src/main/java/app/Cart.java
src/main/java/app/Main.java
src/main/resources/application.properties
src/test/java/app/CartTest.java
target skipped: true
Step by step:
preVisitDirectoryis called before a directory's contents are visited. It creates the matching directory under the target, so the folder exists before any file is copied into it.- Mapping paths:
source.relativize(dir)gives the path inside the project (src/main/java), andtarget.resolve(...)places it under the backup folder. The same mapping is used for files. This relativize-then-resolve technique is the standard way to mirror one tree into another. - Skipping subtrees: for
targetand.git, the visitor returnsSKIP_SUBTREE, so nothing inside them is visited. The root is excluded from this check by!dir.equals(source). visitFilecopies each file.REPLACE_EXISTINGlets the backup be refreshed by running the copy again;COPY_ATTRIBUTESkeeps the original modification times (and permissions where supported), which matters for backups and build tools that compare timestamps.- The result contains the 7 source and documentation files, without build output or Git data.
FileVisitResult has four values: CONTINUE, SKIP_SUBTREE (only meaningful from preVisitDirectory), SKIP_SIBLINGS (skip the rest of the current directory) and TERMINATE (stop the whole walk).
Moving and Renaming Directories
import java.io.IOException;
import java.nio.file.*;
public class Move {
public static void main(String[] args) throws IOException {
Path drafts = Files.createDirectories(Path.of("content/drafts/java-streams"));
Files.writeString(drafts.resolve("index.md"), "# Streams");
Path published = Files.createDirectories(Path.of("content/published"));
Path moved = Files.move(drafts, published.resolve("java-streams"));
System.out.println("moved to " + moved + ", file inside: " + Files.exists(moved.resolve("index.md")));
Path renamed = Files.move(moved, moved.resolveSibling("java-streams-api"));
System.out.println("renamed to " + renamed.getFileName());
try {
Files.move(Path.of("content/published"), Path.of("content"));
} catch (IOException e) {
System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());
}
}
}
Output:
moved to content/published/java-streams, file inside: true
renamed to java-streams-api
FileAlreadyExistsException: content
Files.move(source, target)moves a directory with all its contents when the move stays on the same file system, because only the directory's entry is relocated — the contents don't have to be copied. It returns the target path.- Renaming is just a move within the same parent:
resolveSiblingbuilds the new name. - The target must not exist, unless you pass
REPLACE_EXISTING(which can only replace an empty directory or a file). Otherwise it throwsFileAlreadyExistsException, as in the last call. - Across file systems (for example, from a local disk to a network drive), a non-empty directory can't be moved in one step;
Files.movethrowsDirectoryNotEmptyException. The solution is to copy the tree (as above) and then delete the source.
Watching a Directory for Changes
Some applications must react when files appear: an import service that processes every CSV dropped into an inbox folder, or a development server that reloads when templates change. Polling the directory with Files.list in a loop works but wastes resources. A WatchService asks the operating system to report changes.
import java.io.IOException;
import java.nio.file.*;
import java.util.concurrent.TimeUnit;
import static java.nio.file.StandardWatchEventKinds.*;
public class Watch {
public static void main(String[] args) throws IOException, InterruptedException {
Path inbox = Files.createDirectories(Path.of("inbox"));
try (WatchService watcher = FileSystems.getDefault().newWatchService()) {
inbox.register(watcher, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE);
Thread producer = new Thread(() -> {
try {
Thread.sleep(200);
Path f = Files.writeString(inbox.resolve("order-1001.json"), "{}");
Thread.sleep(200);
Files.delete(f);
} catch (Exception e) {
throw new RuntimeException(e);
}
});
producer.start();
int seen = 0;
while (seen < 2) {
WatchKey key = watcher.poll(5, TimeUnit.SECONDS);
if (key == null) break;
for (WatchEvent<?> event : key.pollEvents()) {
if (event.kind() == OVERFLOW) continue;
Path name = (Path) event.context();
System.out.println(event.kind().name() + " " + name);
if (event.kind() != ENTRY_MODIFY) seen++;
}
if (!key.reset()) break;
}
producer.join();
}
}
}
Output (on Linux; the exact events can differ between operating systems):
ENTRY_CREATE order-1001.json
ENTRY_MODIFY order-1001.json
ENTRY_DELETE order-1001.json
How it works:
newWatchService()creates the watcher; it'sCloseable, so it's managed with try-with-resources.registersubscribes the directory to the event kinds you care about. Only that directory is watched, not its subdirectories — each subdirectory needs its own registration.- A second thread simulates another program: it creates a file and then deletes it.
poll(5, SECONDS)waits up to five seconds for aWatchKeywith pending events and returnsnullon timeout. (take()waits indefinitely.)pollEvents()returns the events.event.context()is the file name relative to the watched directory; useinbox.resolve(name)for the full path.OVERFLOWmeans events were lost because too many happened at once, and a robust application rescans the directory when it sees one.key.reset()must be called after processing, or the key won't deliver any further events. It returnsfalsewhen the directory is no longer accessible (for example, it was deleted).
Writing a file usually produces a CREATE event followed by one or more MODIFY events, and the CREATE can arrive before the writer has finished. Import services therefore commonly have producers write to a temporary name (order-1001.json.part) and rename it when complete, and only process names that match the final pattern. On some platforms (notably macOS), the JDK's watch service polls internally, so events can arrive several seconds late.