Lesson 18 of 23
In progress
Reading and writing files
Read a whole file or stream it line by line, write text safely, and handle encodings and paths without surprises.
Files are the simplest form of persistence and the most common source of small bugs: an unclosed handle, a wrong encoding, a path that works on one operating system and not another.
What you will learn
- Read a small file in one call and a large one line by line.
- Write text, appending or replacing.
- Handle paths and encodings explicitly.
Paths
import java.nio.file.Path;
import java.nio.file.Paths;
Path relative = Paths.get("data", "orders.csv");
Path absolute = relative.toAbsolutePath();
System.out.println(absolute);
Path replaces the old File class and handles separators for you. Paths.get("data", "orders.csv") produces data/orders.csv on Unix and dataorders.csv on Windows, which is why you should never concatenate separators by hand.
Path.resolve joins: base.resolve("orders.csv"). getParent, getFileName and normalize are the ones you will use most.
The working directory
A relative path resolves against the process’s working directory, not against the source file. An IDE launches the program from the project root while a terminal may launch it from build/classes, so data/orders.csv can work in one and fail in the other with NoSuchFileException.
When a file cannot be found, print Path.of(path).toAbsolutePath() in the error message. That one line distinguishes a wrong path from a wrong working directory, and it is the single most useful diagnostic in file handling.
Reading a whole file
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
static String read(String path) throws IOException {
return Files.readString(Path.of(path));
}
Files.readString reads the entire file as text with UTF-8 by default. It is perfect for configuration and small data files, and wrong for a multi-gigabyte log, which would be loaded into memory at once.
For lines:
java.util.List<String> lines = Files.readAllLines(Path.of("data/orders.csv"));
That is convenient for a few thousand lines and again loads everything.
Streaming a large file
import java.io.BufferedReader;
import java.nio.file.Files;
import java.nio.file.Path;
static int countLines(String path) throws java.io.IOException {
int count = 0;
try (BufferedReader reader = Files.newBufferedReader(Path.of(path))) {
while (reader.readLine() != null) {
count++;
}
}
return count;
}
newBufferedReader uses UTF-8 by default and returns a reader that must be closed, which try-with-resources does on every path. Only one line is in memory at a time, so the file size stops mattering.
Files.lines(path) gives a stream and must also be closed:
try (var lines = Files.lines(Path.of(path))) {
lines.filter(line -> line.contains("ERROR")).forEach(System.out::println);
}
Writing
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
static void write(String path, String content) throws java.io.IOException {
Files.writeString(Path.of(path), content);
}
static void append(String path, String line) throws java.io.IOException {
Files.writeString(Path.of(path), line + System.lineSeparator(),
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
}
Files.writeString replaces the file, creating it if needed. Passing APPEND keeps existing content and adds to the end, which is what a log needs.
Writing to a temporary file and moving it into place is the safe pattern for anything important: a crash mid-write leaves the original intact.
Path tmp = Path.of("data/orders.csv.tmp");
Files.writeString(tmp, content);
Files.move(tmp, Path.of("data/orders.csv"),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
Encodings
Text is bytes plus an encoding. UTF-8 is the default in the java.nio.file methods and the right choice for new files. Reading a file written in another encoding without saying so produces mojibake, which is hard to recognise as an encoding problem.
java.nio.charset.Charset windows = java.nio.charset.Charset.forName("windows-1252");
Files.readString(Path.of("legacy.txt"), windows);
When a file has a byte-order mark, the first character may appear as an invisible extra character. uFEFF at the start of the string is the usual symptom; strip it when parsing.
A CSV reader
static java.util.List<String[]> readCsv(String path) throws java.io.IOException {
java.util.List<String[]> rows = new java.util.ArrayList<>();
try (BufferedReader reader = Files.newBufferedReader(Path.of(path))) {
String line;
boolean first = true;
while ((line = reader.readLine()) != null) {
if (first) {
first = false;
continue;
}
if (line.isBlank()) {
continue;
}
rows.add(line.split(",", -1));
}
}
return rows;
}
split(",", -1) keeps trailing empty fields, which the one-argument version drops. That matters for a row like a,b, where the last column is intentionally empty.
Real CSV has quoted fields containing commas and newlines. For anything beyond simple data, use a library; hand-written parsers fail on the first quoted comma.
Errors you will meet
NoSuchFileException— the path is wrong, or the working directory is not what you think.AccessDeniedException— file permissions.FileAlreadyExistsException— a create withoutREPLACE_EXISTING.MalformedInputException— the bytes are not valid in the chosen encoding.
Each has a distinct cause, and the exception type tells you which. Printing the absolute path in the error message saves time.
Reading a file with new FileReader(path), which uses the platform default encoding. The same file then parses on one machine and fails on another. Use Files.newBufferedReader or pass the charset.
Write a method that reads a text file and writes a copy with line numbers prefixed, padded to four characters. Skip blank lines in the count.
Show solution
import java.io.BufferedReader; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; static void numbered(String in, String out) throws java.io.IOException { List<String> result = new ArrayList<>(); int n = 0; try (BufferedReader reader = Files.newBufferedReader(Path.of(in))) { String line; while ((line = reader.readLine()) != null) { if (line.isBlank()) { result.add(""); continue; } n++; result.add(String.format("%04d %s", n, line)); } } Files.write(Path.of(out), result); } Files.write writes a list of lines with the platform separator. The counter only increments for non-blank lines, and blank lines are preserved so the output still lines up with the input.
Recap
- Use
PathandFiles; read small files whole and stream large ones. - Always close readers and streams with try-with-resources, and specify UTF-8.
- Write via a temporary file when a partial write would be harmful.
Module 6 covers the tooling around real Java: build tools, tests, streams and a capstone.
What is the difference between File and Path?
How do I read a file from resources?
Progress is saved in this browser only. No account, no email.