Explain it simply
Explain it simply
Think of a Path as a street address: "reports/2026/summary.txt" only says where something lives, and creating the Path does not even check that the place exists. Files is the courier who actually goes to that address to write, read, copy or delete.
The courier's trip can fail: the file may be missing, the folder may not exist, permission may be denied or the disk may be full, so most Files methods throw IOException. Every piece of file I/O code therefore needs a plan for what happens when the trip fails.
Problem → Why → Solution
The problem: file code that works on your laptop and breaks on the server
Three problems hide in the code below. First, getBytes() and new String() without a charset use the platform default, which before Java 18 could differ between a Windows laptop and a Linux server, so text like "café" can turn into garbage. Second, the user-supplied name is never checked, so a value like "../../etc/passwd" reads a file outside the uploads folder.
Third, if the reports folder does not exist yet, write() throws NoSuchFileException and the program stops.
import java.nio.file.*;
public class Main {
public static void main(String[] args) throws Exception {
String name = args[0]; // e.g. "../../etc/passwd"
Path upload = Path.of("uploads", name); // never validated
String text = new String(Files.readAllBytes(upload)); // platform charset
Files.write(Path.of("reports/out.txt"), text.getBytes()); // folder may not exist
}
}Why don't these bugs show up early?
On the developer's machine the folders already exist, the charset happens to match and every file name you type is harmless. The fix is to always pass StandardCharsets.UTF_8 explicitly, create parent folders with Files.createDirectories(), and normalize any path built from user input before checking that it stays under an allowed root.
Core concept: Path is the address, Files does the work
You build a Path with Path.of("data", "notes.txt"). That beats gluing strings together, because Java handles the separator (/ or \) for each operating system. resolve() appends a part to a folder path, getFileName() and getParent() split a path apart, and normalize() removes "." and ".." segments. None of these methods touch the disk: a Path is just an immutable value object.
The work that really touches the disk is done by static methods on the Files class. For small files, Files.writeString() and Files.readString(), available since Java 11, do the job in one line, and Files.readAllLines() returns the lines as a List<String>. All three load the whole file into memory, so for log files of hundreds of megabytes you read line by line with Files.newBufferedReader() or Files.lines().
Know the defaults of the write methods. With no options, writeString() creates the file if it is missing and otherwise replaces its old content (CREATE, TRUNCATE_EXISTING, WRITE). To add to the end you pass StandardOpenOption.APPEND, together with CREATE if the file might not exist yet. As for charsets, Files methods use UTF-8 when you pass none, but writing StandardCharsets.UTF_8 explicitly tells every reader of the code what you intended.
Most Files methods throw the checked IOException. Common subclasses are NoSuchFileException when a file is missing, FileAlreadyExistsException when the file you want to create is already there, and DirectoryNotEmptyException when you delete a folder that still has content. Catching the specific subclass lets you react differently to "the file is not there yet, use a default" and "the disk is broken, stop". Methods that open a stream or reader must always be closed with try-with-resources, or the operating system can run out of file handles.
- Build the address with Path
- Check user paths stay under root
- Read or write with Files + UTF-8
- Handle the IOException
- Close resources, delete temp files
Creating a Path never fails on a missing file; touching the disk through Files is where things fail.
General pattern
Path file = Path.of("folder", "name.txt");
Files.createDirectories(file.getParent());
Files.writeString(file, text, StandardCharsets.UTF_8);
Files.writeString(file, more, StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
String all = Files.readString(file, StandardCharsets.UTF_8);
try (BufferedReader in = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
String line;
while ((line = in.readLine()) != null) { handle(line); }
}Build the address with Path.of() and make sure the parent folder exists with createDirectories(). writeString() replaces the content, while APPEND adds to the end. Use readString() for small files and a BufferedReader line by line for large ones, closing the reader with try-with-resources.
Example: write and read back a temporary file
This example creates a uniquely named file in the operating system's temp folder, writes to it in UTF-8, reads it back, and deletes it in finally. Using a temp file guarantees you never overwrite a real file in your project by accident.
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
class Main {
public static void main(String[] args) throws Exception {
Path file = Files.createTempFile("java-notes-", ".txt");
try {
Files.writeString(file, "Safe Java I/O", StandardCharsets.UTF_8);
System.out.println(Files.readString(file, StandardCharsets.UTF_8));
} finally {
Files.deleteIfExists(file);
}
}
}Code breakdown
- Line 6
public static void main(String[] args) throws Exception {Files methods throw the checked IOException, so main() declares throws. That is fine for a demo, but real code should declare the more precise throws IOException.
- Line 7
Path file = Files.createTempFile("java-notes-", ".txt");Creates an empty file in the temp folder whose name starts with java-notes- and ends with .txt. A random middle part gives each run a different name.
- Line 9
Files.writeString(file, "Safe Java I/O", StandardCharsets.UTF_8);Encodes the string as UTF-8 bytes and writes them. With no options, any existing content in the file is replaced.
- Line 10
System.out.println(Files.readString(file, StandardCharsets.UTF_8));Reads the bytes back with the same charset used for writing. Writing and reading with different charsets is how text gets garbled.
- Lines 11-12
Files.deleteIfExists(file);Placed in finally, so the temp file is deleted even if writing or reading failed. deleteIfExists() returns false instead of throwing when the file is already gone.
Safe Java I/OAppending and reading line by line
For files that can grow large, such as logs, write with a BufferedWriter and read one line at a time with a BufferedReader. The program below writes a log file in a temp folder and counts its WARN lines. Both the writer and the reader live in try-with-resources, so they are closed, and the writer's buffer is flushed to disk, as soon as each block ends.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class Main {
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("io-demo-");
Path log = dir.resolve("app.log");
try {
try (BufferedWriter out = Files.newBufferedWriter(log, StandardCharsets.UTF_8)) {
out.write("INFO started");
out.newLine();
out.write("WARN disk 91%");
out.newLine();
}
Files.writeString(log, "INFO stopped\n", StandardCharsets.UTF_8,
StandardOpenOption.APPEND);
int warnings = 0;
try (BufferedReader in = Files.newBufferedReader(log, StandardCharsets.UTF_8)) {
String line;
while ((line = in.readLine()) != null) {
if (line.startsWith("WARN")) warnings++;
}
}
int total = Files.readAllLines(log, StandardCharsets.UTF_8).size();
System.out.println("Lines: " + total);
System.out.println("Warnings: " + warnings);
System.out.println("File name: " + log.getFileName());
} finally {
Files.deleteIfExists(log);
Files.deleteIfExists(dir);
}
}
}The output is Lines: 3, Warnings: 1, File name: app.log. Note that it prints only getFileName() rather than the absolute temp path, which differs on every machine. Also note that newLine() writes the platform's line separator: \r\n on Windows and \n on Linux.
Handling missing files and folders
A missing file is often a normal case, such as a settings file that does not exist on the first run, so you can catch NoSuchFileException specifically and fall back to a default. Before writing into nested folders, Files.createDirectories() creates every missing parent and does nothing if they already exist.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("missing-demo-");
try {
Path settings = dir.resolve("settings.txt");
System.out.println("Exists: " + Files.exists(settings));
try {
Files.readString(settings);
} catch (NoSuchFileException e) {
System.out.println("Not found: " + Path.of(e.getFile()).getFileName());
}
Path nested = dir.resolve("reports/2026/summary.txt");
Files.createDirectories(nested.getParent());
Files.writeString(nested, "ok");
System.out.println("Nested written: " + Files.readString(nested));
System.out.println("Parent folder: " + nested.getParent().getFileName());
Files.delete(nested);
Files.delete(nested.getParent());
Files.delete(nested.getParent().getParent());
} finally {
Files.deleteIfExists(dir);
}
}
}In real projects
Where this shows up in real projects
Backend applications use file I/O to export CSV reports, store uploaded files on disk, read configuration and let batch jobs process data files. An upload feature never trusts the user's file name directly: the server either generates its own name, such as a UUID, or checks the result of resolve().normalize() with startsWith(root), because path traversal with "../" is a common security bug.
When updating a file, a common pattern is to write a new temp file next to it and swap it in with Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE) instead of overwriting in place. If the process dies mid-write, the old file is still intact. Unit tests also create a private folder per test with createTempDirectory(), as in this lesson, and delete it afterwards; JUnit 5's @TempDir does that automatically.
Common mistakes
Common mistakes
1. Forgetting APPEND and wiping old data
Calling Files.writeString(file, note) to add one more note erases every existing note, because the default includes TRUNCATE_EXISTING. Pass StandardOpenOption.CREATE and StandardOpenOption.APPEND when you mean to add.
2. Leaving Files.lines() open
Files.lines() and Files.walk() return a Stream that holds an open file handle. Without try-with-resources the handles leak, which shows up as files you cannot delete on Windows or "Too many open files" errors on a server.
3. Checking startsWith() without normalize()
root.resolve("../secret.txt") still contains the ".." segment, so startsWith(root) returns true and the check protects nothing. Call normalize() before startsWith().
4. Printing absolute temp paths
Temp paths differ per machine and can leak details such as the user name. Show getFileName() or a relativize() result instead.
Mini challenge
Mini challenge: a safe notes store
Use a temp folder as the notes root: append notes to notes.txt, read them back and print them numbered. Block file names that escape the root, handle reading a missing file, and delete the whole folder at the end.
- safeResolve(root, name) resolves and normalizes, throwing IllegalArgumentException outside the root
- addNote() appends one note as a line, using UTF-8, CREATE and APPEND
- Print the note count and lines in the form "1. buy milk"
- Block "../secret.txt" and catch NoSuchFileException for the missing archive.txt
- In finally, delete the whole folder using Files.walk() in try-with-resources; never print absolute paths
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Stream;
public class Main {
static Path safeResolve(Path root, String name) {
// TODO: resolve + normalize, then reject anything outside root
return root;
}
static void addNote(Path file, String note) throws IOException {
// TODO: append note plus a newline (UTF-8, CREATE, APPEND)
}
static void deleteTree(Path root) throws IOException {
// TODO: walk the tree (close the stream!) and delete deepest paths first
}
public static void main(String[] args) throws IOException {
Path root = Files.createTempDirectory("notes-").toAbsolutePath().normalize();
try {
// TODO: add three notes, read them back, print them numbered
// TODO: try "../secret.txt" and a missing "archive.txt"
} finally {
deleteTree(root);
}
}
}Expected: The program should print: Notes: 3 1. buy milk 2. call Aye 3. pay rent Blocked: outside the notes folder: ../secret.txt Missing: archive.txt Cleaned up: true
Show hint
Files.walk(root) returns parents before their children, so sorting with Comparator.reverseOrder() deletes the innermost files first and the folder last. NoSuchFileException.getFile() returns the path as a string, so take just the name with Path.of(...).getFileName().
Show solution
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Stream;
public class Main {
static Path safeResolve(Path root, String name) {
Path target = root.resolve(name).normalize();
if (!target.startsWith(root)) {
throw new IllegalArgumentException("outside the notes folder: " + name);
}
return target;
}
static void addNote(Path file, String note) throws IOException {
Files.writeString(file, note + "\n", StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
}
static void deleteTree(Path root) throws IOException {
try (Stream<Path> paths = Files.walk(root)) {
for (Path p : paths.sorted(Comparator.reverseOrder()).toList()) {
Files.delete(p);
}
}
}
public static void main(String[] args) throws IOException {
Path root = Files.createTempDirectory("notes-").toAbsolutePath().normalize();
try {
Path notes = safeResolve(root, "notes.txt");
addNote(notes, "buy milk");
addNote(notes, "call Aye");
addNote(notes, "pay rent");
List<String> lines = Files.readAllLines(notes, StandardCharsets.UTF_8);
System.out.println("Notes: " + lines.size());
for (int i = 0; i < lines.size(); i++) {
System.out.println((i + 1) + ". " + lines.get(i));
}
try {
safeResolve(root, "../secret.txt");
} catch (IllegalArgumentException e) {
System.out.println("Blocked: " + e.getMessage());
}
try {
Files.readString(safeResolve(root, "archive.txt"), StandardCharsets.UTF_8);
} catch (NoSuchFileException e) {
System.out.println("Missing: " + Path.of(e.getFile()).getFileName());
}
} finally {
deleteTree(root);
}
System.out.println("Cleaned up: " + !Files.exists(root));
}
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A Path is an address value that never touches the disk; the static methods on Files do the real work.
- Always pass StandardCharsets.UTF_8; writeString() overwrites by default and only APPEND adds to the end.
- Read large files with a BufferedReader or Files.lines(), and close streams and readers with try-with-resources.
- Normalize user-supplied paths before checking startsWith(root), and clean up temp files in finally.
java.nio.file API — Oracle