Java Directory Handling

Su Suriya Ravichandran Updated 18 Nov 2026
12 min read ·Lesson 146 of 306

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:

TaskMethod
Create one directory / a whole chainFiles.createDirectory(dir) / Files.createDirectories(dir)
List direct entriesFiles.list(dir), Files.newDirectoryStream(dir[, glob])
Visit a whole treeFiles.walk(dir[, maxDepth]), Files.find(...), Files.walkFileTree(...)
Move or renameFiles.move(source, target)
DeleteFiles.delete(dir) (empty directories only)
React to changesWatchService

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 other Files methods; 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. Path sorting compares names character by character, so uppercase README.md sorts 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. (Compare File.listFiles(), which returns null for 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.

GlobMatches
*.csvNames 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 why main and test appear 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, walk answers most "find files in this tree" questions: filter regular files, match a name, and relativize against 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 throws FileSystemLoopException instead of looping forever.
  • An unreadable directory stops the stream: walk and find throw UncheckedIOException (wrapping, for example, AccessDeniedException) when the stream reaches it. To skip such directories and continue, use walkFileTree and override visitFileFailed.
  • 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:

  1. Test files are created with Files.write(path, new byte[n]), which writes n zero bytes — a quick way to make files of an exact size.
  2. Files.walk(site) supplies every path in the tree; filter(Files::isRegularFile) keeps only files.
  3. 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.
  4. size wraps IOException in UncheckedIOException, because Files.size throws 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.
  5. 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:

  1. preVisitDirectory is 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.
  2. Mapping paths: source.relativize(dir) gives the path inside the project (src/main/java), and target.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.
  3. Skipping subtrees: for target and .git, the visitor returns SKIP_SUBTREE, so nothing inside them is visited. The root is excluded from this check by !dir.equals(source).
  4. visitFile copies each file. REPLACE_EXISTING lets the backup be refreshed by running the copy again; COPY_ATTRIBUTES keeps the original modification times (and permissions where supported), which matters for backups and build tools that compare timestamps.
  5. 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: resolveSibling builds 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 throws FileAlreadyExistsException, 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.move throws DirectoryNotEmptyException. 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:

  1. newWatchService() creates the watcher; it's Closeable, so it's managed with try-with-resources.
  2. register subscribes the directory to the event kinds you care about. Only that directory is watched, not its subdirectories — each subdirectory needs its own registration.
  3. A second thread simulates another program: it creates a file and then deletes it.
  4. poll(5, SECONDS) waits up to five seconds for a WatchKey with pending events and returns null on timeout. (take() waits indefinitely.)
  5. pollEvents() returns the events. event.context() is the file name relative to the watched directory; use inbox.resolve(name) for the full path. OVERFLOW means events were lost because too many happened at once, and a robust application rescans the directory when it sees one.
  6. key.reset() must be called after processing, or the key won't deliver any further events. It returns false when 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Directory Handling and get answers drawn from it.

Signed-in readers only.