Files Class in Java (NIO.2): Read, Write, Copy and Search Files
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
Swipe sideways to see the whole diagram.
3. Commonly Used Methods
| Method | Description |
|---|---|
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.
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));
}
}
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
createDirectories()createsdocsanddocs/draftsin one call.writeString()saves the text, andsize()reports 33 bytes.copy()keeps a version-1 copy;move()moves the draft, so it no longer exists indrafts.mismatch()returns-1, so the copy and the published file are identical.- 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.
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());
}
}
}
Found: app/2026-11/old.log Found: app/app.log Log files: 2, total size: 2000 bytes
How the code works
Files.walk(root)returns a stream of every path in the tree, including sub-folders.- The stream is opened in try-with-resources, because it keeps folders open until it is closed.
filter()keeps.logfiles,sorted()gives a stable order andtoList()(Java 16) collects them.- 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()orwalk(). They hold open file handles; use try-with-resources. - Reading huge files with
readString()orreadAllLines(). Stream them withlines()instead. - Forgetting
REPLACE_EXISTING.copy()andmove()throwFileAlreadyExistsExceptionwithout 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 version | Change |
|---|---|
| Java 7 | Files introduced with NIO.2. |
| Java 8 | lines(), list(), walk(), find(), and UTF-8 defaults for reader, writer and line methods. |
| Java 11 | readString() and writeString(). |
| Java 12 | mismatch(). |
| Java 25 | All of the above are standard; no changes to Files. |
8. Summary
Filesoffers static methods for nearly every file and folder task.- It works with
Pathobjects and throws descriptive exceptions. readString()andwriteString()handle small text files in one line.- Close the streams from
lines(),list()andwalk(). - Use
REPLACE_EXISTINGto overwrite, and delete folders deepest first.