Sub topic 8
Buffered readers and writers
This chapter assumes you know the Path and Files basics, try-with-resources, checked exceptions, and why a charset must be named explicitly. It covers how to process a text file one line at a time without loading it all into memory.
Why buffering exists
Files.readString and Files.readAllLines put the whole file in memory. That is fine for a configuration file and a problem for a 4 GB log. A BufferedReader solves this by reading a block of characters from the file at once, keeping it in an internal array, and handing it to you piece by piece. A BufferedWriter does the reverse. It collects your writes in memory and sends them to the operating system in large blocks.
The reason is cost. Each call that reaches the operating system is slow compared with copying characters inside an array. Without a buffer, a loop that writes one line at a time makes one system call per line. With a buffer, it makes one call per block.
Creating buffered streams from a Path
Files has two factory methods for this:
Files.newBufferedReader(Path, Charset)returns aBufferedReader.Files.newBufferedWriter(Path, Charset, OpenOption...)returns aBufferedWriter.
Both have overloads that omit the charset and use UTF-8. Naming the charset anyway makes your intent visible to the next reader. The default buffer size is 8192 characters.
Here is a complete program that reads a file and writes an upper-case copy:
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;
public class CopyUpperCase {
public static void main(String[] args) throws IOException {
Path in = Path.of("input.txt");
Path out = Path.of("output.txt");
try (BufferedReader reader = Files.newBufferedReader(in, StandardCharsets.UTF_8);
BufferedWriter writer = Files.newBufferedWriter(out, StandardCharsets.UTF_8)) {
String line;
while ((line = reader.readLine()) != null) {
writer.write(line.toUpperCase());
writer.newLine();
}
}
}
}At most one line plus the buffers is in memory at any time, so this works on files of any size.
How the loop works
readLine() returns the next line without its terminator. It recognizes \n, \r and \r\n as terminators. At end of file it returns null, not an empty string. The idiom (line = reader.readLine()) != null assigns and tests in one expression.
writer.newLine() writes the platform line separator, taken from the line.separator system property. That is \r\n on Windows and \n on Linux and macOS. Use newLine() when the file should follow the local convention. If you need a fixed ending, for example \n for a file that goes to Linux servers, write "\n" yourself.
Open options for writers
newBufferedWriter follows the same rule as Files.writeString. With no options, it uses CREATE, TRUNCATE_EXISTING and WRITE. If you pass any options, they replace those defaults. To append to a log and create it if it is missing, name both:
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 AppendLines {
public static void main(String[] args) throws IOException {
Path log = Path.of("app.log");
try (BufferedWriter writer = Files.newBufferedWriter(log, StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.APPEND)) {
writer.write("job started");
writer.newLine();
writer.write("job finished");
writer.newLine();
}
}
}If you passed only APPEND and the file did not exist, you would get a NoSuchFileException. Passing CREATE_NEW instead of CREATE fails with FileAlreadyExistsException when the file exists, which is useful when you must not overwrite anything.
Closing and flushing
A BufferedWriter holds data that has not yet reached the file. Three things push it out:
- The buffer fills up.
- You call
flush(). - You call
close(), which flushes first.
Try-with-resources calls close() for you, so you rarely need flush(). If you forget to close a writer, the last partial buffer is silently lost and the file ends early. That is the most common bug with buffered output.
Resources close in reverse order of declaration. In the copy example, the writer closes first and then the reader. If both the body and a close() throw, the body's exception is the one you see. The close() failure is attached to it as a suppressed exception, available through getSuppressed(). A failure in the writer's close() matters. It can mean the final block was not written, for example because the disk is full. So do not swallow exceptions from the try statement.
Encoding errors
The readers and writers from Files are strict. If a byte sequence is not valid in the charset you named, readLine() throws MalformedInputException. This is a subclass of IOException, in java.nio.charset. The older new FileReader(...) and InputStreamReader classes instead replace bad bytes with the character \uFFFD and carry on, which hides corruption.
When a file is in a legacy encoding, name that charset instead of catching the exception and retrying:
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.MalformedInputException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class ReadLegacy {
public static void main(String[] args) throws IOException {
Path file = Path.of("legacy.txt");
try (BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (MalformedInputException e) {
System.out.println("Not valid UTF-8. Try ISO_8859_1 if you know the file is Latin-1.");
}
}
}ISO_8859_1 maps every byte to a character, so it never throws. That also means it can produce wrong text without any warning, so use it only when you know the file's encoding.
Line-by-line behavior to remember
readLine()cannot tell you whether the last line had a terminator. A file ending in"a\nb"and one ending in"a\nb\n"both give you two lines.- A blank line comes back as
"", notnull. Only end of file givesnull. - Files with a UTF-8 byte order mark keep it as
\uFEFFat the start of the first line. Java's UTF-8 decoder does not remove it. BufferedReaderis not thread-safe for concurrent reads of the same instance. Give each thread its own reader.
Changing the buffer size
The default suits most work. If profiling shows that large sequential transfers are slow, wrap the stream yourself with a larger buffer:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class BigBuffers {
public static void main(String[] args) throws IOException {
Path in = Path.of("input.txt");
Path out = Path.of("output.txt");
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(Files.newInputStream(in), StandardCharsets.UTF_8), 65536);
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(Files.newOutputStream(out), StandardCharsets.UTF_8), 65536)) {
reader.transferTo(writer);
}
}
}Reader.transferTo(Writer) has existed since Java 10. It copies all remaining characters. Measure before you tune. Past a few tens of kilobytes, a larger buffer rarely helps.
Choosing between the tools
| Need | Use |
|---|---|
| Small file, whole content as one value | `Files.readString`, `Files.readAllLines` |
| Large file, plain loop, explicit control | `BufferedReader` with `readLine()` |
| Large file, stream pipeline | `Files.lines` (next chapter) |
| Many small writes to one file | `BufferedWriter` |
| One write of a prepared string | `Files.writeString` |
A BufferedReader also offers lines(), which returns a Stream<String> over the same reader. This lets you use a stream pipeline while keeping the reader's charset and lifetime under your control.
Exercise
A program writes 10,000 lines through a BufferedWriter created with Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.APPEND). It is not in a try-with-resources block and never calls close(). The target file does not exist yet. What goes wrong, and what are the two separate fixes?
Show answer
Two problems occur. First, APPEND without CREATE makes the call throw NoSuchFileException because the file is missing, so nothing is written. Add StandardOpenOption.CREATE. Second, even with that fixed, never closing the writer leaves the final partial buffer unflushed, so the file would end early. Create the writer in a try-with-resources header so close() flushes and releases the file.