00:00

Files Class in Java (NIO.2): Read, Write, Copy and Search Files

Last updated:

Copying a file, reading it into a string, creating nested folders or searching a whole folder tree each take a single method call with java.nio.file.Files. It is the modern, all-purpose toolbox for file work in Java.

This tutorial groups its most useful methods by task and shows two practical examples.

1. What Is the Files Class in Java?

Files is a final utility class added in Java 7. It contains only static methods that operate on Path objects. Its methods throw clear exceptions, such as NoSuchFileException, FileAlreadyExistsException and DirectoryNotEmptyException, when something goes wrong.

2. Files Methods at a Glance

Files class methods grouped by taskThe final class java.nio.file.Files, added in Java 7, contains only static methods. Check: exists, notExists, isDirectory, isRegularFile, size and getLastModifiedTime. Read: readString from Java 11, readAllLines, readAllBytes, lines and newBufferedReader. Write: writeString from Java 11, write with a list of lines and newBufferedWriter. Create: createFile, createDirectory, createDirectories and the temporary file and directory methods. Copy, move and delete: copy, move, delete, deleteIfExists and mismatch from Java 12. Folders: list, walk, find and newDirectoryStream.java.nio.file.Filesfinal class with static methods, Java 7Checkexists(), notExists()isDirectory(), isRegularFile()size(), getLastModifiedTime()ReadreadString() Java 11readAllLines(), readAllBytes()lines(), newBufferedReader()WritewriteString() Java 11write(path, lines)newBufferedWriter()CreatecreateFile(), createDirectory()createDirectories()createTempFile/Directory()Copy, move, deletecopy(), move()delete(), deleteIfExists()mismatch() Java 12Folderslist()walk(), find()newDirectoryStream()

Swipe sideways to see the whole diagram.

3. Commonly Used Methods

MethodDescription
readString(path) / writeString(path, text)Read or write a whole text file as UTF-8 (Java 11).
readAllLines(path) / lines(path)All lines as a List, or a lazily read Stream (Java 8).
createDirectories(path)Creates a folder and any missing parents.
copy(source, target, options...)Copies a file; REPLACE_EXISTING overwrites the target.
move(source, target, options...)Moves or renames; ATOMIC_MOVE requests an atomic move.
delete(path) / deleteIfExists(path)Deletes; the second returns false instead of throwing if nothing exists.
exists(path) / size(path)Checks existence; returns the size in bytes.
list(dir) / walk(start)One folder level, or the whole tree, as a Stream<Path> (Java 8).
mismatch(a, b)Position of the first different byte, or -1 if identical (Java 12).

4. Example: Create, Copy, Move and Delete

A shop publishes its terms of service: it writes a draft, keeps a copy as version 1 and moves the draft to the public folder.

FilesTour.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

public class FilesTour {
    public static void main(String[] args) throws IOException {
        Path root = Files.createTempDirectory("shop");
        Path drafts = Files.createDirectories(root.resolve("docs").resolve("drafts"));   // creates both folders

        Path terms = drafts.resolve("terms.txt");
        Files.writeString(terms, "Returns accepted within 30 days.\n");                 // Java 11
        System.out.println("Exists: " + Files.exists(terms) + ", size: " + Files.size(terms) + " bytes");

        Path copy = Files.copy(terms, root.resolve("terms-v1.txt"));
        Path published = Files.move(terms, root.resolve("docs").resolve("terms.txt"), StandardCopyOption.REPLACE_EXISTING);
        System.out.println("Copy identical: " + (Files.mismatch(copy, published) == -1));   // Java 12
        System.out.println("Draft still there: " + Files.exists(terms));
        System.out.print("Published text: " + Files.readString(published));

        Files.delete(published);
        Files.delete(copy);
        Files.delete(drafts);
        Files.delete(drafts.getParent());
        Files.delete(root);
        System.out.println("Cleaned up: " + Files.notExists(root));
    }
}
Output
Exists: true, size: 33 bytes
Copy identical: true
Draft still there: false
Published text: Returns accepted within 30 days.
Cleaned up: true

How the code works

  1. createDirectories() creates docs and docs/drafts in one call.
  2. writeString() saves the text, and size() reports 33 bytes.
  3. copy() keeps a version-1 copy; move() moves the draft, so it no longer exists in drafts.
  4. mismatch() returns -1, so the copy and the published file are identical.
  5. The files and then the empty folders are deleted, deepest first.

5. Example: Finding Log Files in a Folder Tree

A server maintenance script finds every .log file below a folder and reports their total size.

LogFinder.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Stream;

public class LogFinder {
    public static void main(String[] args) throws IOException {
        Path root = Files.createTempDirectory("server");
        Files.createDirectories(root.resolve("app").resolve("2026-11"));
        Files.writeString(root.resolve("app").resolve("app.log"), "x".repeat(1200));
        Files.writeString(root.resolve("app").resolve("2026-11").resolve("old.log"), "x".repeat(800));
        Files.writeString(root.resolve("app").resolve("config.yml"), "port: 8080\n");

        // walk() visits every file and folder below root; close it with try-with-resources
        List<Path> logs;
        try (Stream<Path> tree = Files.walk(root)) {
            logs = tree.filter(p -> p.toString().endsWith(".log")).sorted().toList();   // toList(): Java 16
        }
        long total = 0;
        for (Path log : logs) {
            total += Files.size(log);
            System.out.println("Found: " + root.relativize(log));
        }
        System.out.println("Log files: " + logs.size() + ", total size: " + total + " bytes");

        try (Stream<Path> all = Files.walk(root)) {                  // delete deepest paths first
            all.sorted(Comparator.reverseOrder()).forEach(p -> p.toFile().delete());
        }
    }
}
Output
Found: app/2026-11/old.log
Found: app/app.log
Log files: 2, total size: 2000 bytes

How the code works

  1. Files.walk(root) returns a stream of every path in the tree, including sub-folders.
  2. The stream is opened in try-with-resources, because it keeps folders open until it is closed.
  3. filter() keeps .log files, sorted() gives a stable order and toList() (Java 16) collects them.
  4. A second walk sorted in reverse order deletes the deepest paths first, so every folder is empty when it is deleted.

6. Common Mistakes and Best Practices

  • Not closing lines(), list() or walk(). They hold open file handles; use try-with-resources.
  • Reading huge files with readString() or readAllLines(). Stream them with lines() instead.
  • Forgetting REPLACE_EXISTING. copy() and move() throw FileAlreadyExistsException without it.
  • Deleting a non-empty folder with delete(). Delete its contents first, deepest first.
  • Checking exists() before every operation. The file can change in between; handle the exception instead.

7. Java Version Improvements and Java 25 Updates

Java versionChange
Java 7Files introduced with NIO.2.
Java 8lines(), list(), walk(), find(), and UTF-8 defaults for reader, writer and line methods.
Java 11readString() and writeString().
Java 12mismatch().
Java 25All of the above are standard; no changes to Files.

8. Summary

  • Files offers static methods for nearly every file and folder task.
  • It works with Path objects and throws descriptive exceptions.
  • readString() and writeString() handle small text files in one line.
  • Close the streams from lines(), list() and walk().
  • Use REPLACE_EXISTING to overwrite, and delete folders deepest first.

Related Tutorials

9. Official Java Documentation References