Java Reading and Writing Files: I/O Streams, Buffered Readers and Files Methods (OCP 21)
Reading and writing files for the OCP 21 exam: read and write loops that return -1, buffers and the read count, flush, BufferedReader.readLine, PrintWriter, append mode, Files.readString, readAllBytes, readAllLines versus lines, newBufferedReader and open options.
kvi5hnuCode Sprout team member8 min readOn this page
Article 87 explained the I/O stream families. This article puts them to work: copying files with I/O streams, then doing the same jobs in one line with the NIO.2 Files helpers. Most exam questions here are about return values (-1, null, byte counts) and about what's held in memory.
Reading and writing with I/O streams
One byte or character at a time
InputStream and Reader both have int read(), and OutputStream and Writer both have void write(int). A minimal copy loop:
void pipe(InputStream source, OutputStream sink) throws IOException {
int next;
while ((next = source.read()) != -1) // -1 means end of stream
sink.write(next);
}
The Reader/Writer version is identical, except that the values are characters. It works, but it makes one method call per byte, which is slow without buffering.
Many bytes at a time
The overloads read(byte[] b) and read(byte[] b, int offset, int length) fill a buffer and return how many values were actually read, or -1 at the end. Reader has the same methods with char[]. Write back only that many:
byte[] buffer = new byte[1024];
int count;
while ((count = in.read(buffer)) > 0)
out.write(buffer, 0, count); // NOT out.write(buffer)

The last read usually fills only part of the buffer. With a 4-byte buffer and the data ABCDEFGHIJ, the reads return 4, 4, 2 and then -1. After the third read the buffer holds IJGH, where GH is left over from the previous read. Writing the whole buffer every time produces ABCDEFGHIJGH.
In read(buffer, offset, length), the offset and length refer to positions in the array: "store up to length values starting at buffer[offset]". They don't refer to positions in the file.
flush()
Output may sit in memory buffers, in Java or in the operating system, before reaching the disk. flush() asks for buffered data to be written now. It's useful to limit data loss if the program crashes, but it's slow if you call it after every write. close() flushes automatically.
Copying text a line at a time
High-level streams make text easy:
void duplicate(File from, File to) throws IOException {
try (var in = new BufferedReader(new FileReader(from));
var out = new BufferedWriter(new FileWriter(to))) {
String line;
while ((line = in.readLine()) != null) {
out.write(line);
out.newLine(); // readLine() removed the line break
}
}
}
readLine()returns the next line without its line terminator, ornullat the end. Noticenull, not-1.newLine()writes the platform's line separator, which is the same asSystem.lineSeparator().new FileReader(...)for a missing file throwsFileNotFoundException, anIOExceptionsubclass.new FileWriter(to)overwrites an existing file.new FileWriter(to, true)andnew FileOutputStream(to, true)append instead.- For binary data, use
BufferedInputStream/BufferedOutputStreamand theirread/writemethods. There are no lines to deal with.
PrintWriter and PrintStream
These add the familiar printing methods to any output stream:
| Method | Does |
|---|---|
print(x) | writes String.valueOf(x) |
println(x) | same, plus the line separator |
printf(...) / format(...) | formatted text (article 90) |
They're the only I/O streams whose methods don't throw IOException. Otherwise every System.out.println would need a try. Errors are recorded instead, and checkError() returns true if anything went wrong.
try (var out = new PrintWriter(new BufferedWriter(new FileWriter("report.txt")))) {
out.print("max temp: ");
out.println(31.5);
out.printf("humidity %d%%%n", 64);
}
System.out and System.err are PrintStreams, and System.in is a plain InputStream.
Common I/O stream methods
| Class | Method | Description |
|---|---|---|
| all input streams | int read() | one byte/char, or -1 at the end |
InputStream / Reader | int read(byte[]) / int read(char[]) | fills the array, returns the count or -1 |
InputStream / Reader | read(array, offset, length) | up to length values, stored from array[offset] |
| all output streams | void write(int) | one byte/char |
OutputStream / Writer | write(array), write(array, offset, length) | writes from an array |
Writer | void write(String) | writes a string |
InputStream | byte[] readAllBytes(), readNBytes(n) | reads everything that's left, or n bytes |
InputStream | long transferTo(OutputStream) | copies the rest of the stream and returns the byte count |
BufferedReader | String readLine() | one line, or null at the end |
BufferedWriter | void newLine() | writes a line separator |
| all output streams | void flush() | pushes buffered data out |
| all streams | void close() | releases the resource. It flushes output streams first. |
Reading and writing with Files
NIO.2 turns common jobs into single calls.
Whole file in memory
String text = Files.readString(path); Files.writeString(out, text);
byte[] bytes = Files.readAllBytes(path); Files.write(out, bytes);
List<String> rows = Files.readAllLines(path); Files.write(out, rows);
All three read the entire file into memory. That's convenient for small files, but a huge file can cause an OutOfMemoryError. Files.write(path, lines) writes each line followed by a line separator. Files.write doesn't accept a String, and writeString doesn't accept a List.
Lazily, one line at a time
try (Stream<String> lines = Files.lines(path)) {
lines.filter(l -> l.startsWith("WARN:"))
.map(l -> l.substring(5))
.forEach(System.out::println);
}
Files.lines() returns a Stream<String> that reads lines as they're needed, so only a small part of the file is in memory. It holds the file open, so close it with try-with-resources.
Factories for I/O streams
When you need a java.io stream for a Path, Files creates it, with UTF-8 as the default for text:
try (BufferedReader r = Files.newBufferedReader(in);
BufferedWriter w = Files.newBufferedWriter(out)) { ... }
try (InputStream i = Files.newInputStream(in);
OutputStream o = Files.newOutputStream(out)) { ... }
Unlike new FileReader(...), a missing file gives NoSuchFileException rather than FileNotFoundException. Both are IOExceptions.
Open options when writing
The Files write methods take optional OpenOption... arguments. With no options, they behave as CREATE, TRUNCATE_EXISTING and WRITE: create the file if needed, otherwise replace its contents.
| Options | Missing file | Existing file |
|---|---|---|
| (none) | creates it | overwrites it |
APPEND | NoSuchFileException | adds to the end |
CREATE, APPEND | creates it | adds to the end |
CREATE_NEW | creates it | FileAlreadyExistsException |
Charsets
The Files text methods always use UTF-8 unless you pass a Charset. Reading a file stored in another encoding throws MalformedInputException as soon as the bytes aren't valid UTF-8. Pass the right charset: Files.readString(path, StandardCharsets.ISO_8859_1).
Files method | Returns / does |
|---|---|
readAllBytes(Path) | byte[] |
readString(Path) | String |
readAllLines(Path) | List<String> |
lines(Path) | lazy Stream<String> |
write(Path, byte[]) | writes bytes |
writeString(Path, CharSequence) | writes text |
write(Path, Iterable<? extends CharSequence>) | writes lines |
newBufferedReader / newBufferedWriter / newInputStream / newOutputStream | I/O stream factories |
What's current
- Java 11 added
Files.readStringandFiles.writeString. Before that, text neededreadAllBytesplusnew String(bytes, charset). - Java 9 to 11 added
InputStream.readAllBytes(),readNBytes(),transferTo()andReader.transferTo().transferToreplaces most hand-written copy loops. - Java 18 made UTF-8 the default for
FileReader/FileWritertoo, sojava.ioand NIO.2 now agree. - The read/write loops are unchanged since Java 1.0, and exam questions still use them.
Exam traps from this article
A complete example
A weather station copies and reports on its log in every style. The program copies bytes one at a time and in chunks, with the classic "ignored count" bug, and copies text line by line with append mode. It prints a report with PrintWriter, reads the log whole with Files, scans warnings lazily with Files.lines(), uses the Files stream factories with readNBytes and transferTo, and tests the open options and charset errors.
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.stream.Stream;
public class Solution {
/** Byte by byte: simple, but one call per byte. */
static void copyByteByByte(InputStream source, OutputStream sink) throws IOException {
int next;
while ((next = source.read()) != -1) sink.write(next);
}
/** In chunks: write only as many bytes as the last read() returned. */
static void copyInChunks(InputStream in, OutputStream out, int size, boolean buggy) throws IOException {
byte[] buffer = new byte[size];
int count;
while ((count = in.read(buffer)) > 0)
out.write(buffer, 0, buggy ? buffer.length : count); // the bug: ignoring count
}
/** Text, line by line, with high-level streams. */
static void copyText(File from, File to) throws IOException {
try (var reader = new BufferedReader(new FileReader(from, StandardCharsets.UTF_8));
var writer = new BufferedWriter(new FileWriter(to, StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) { // readLine() drops the line break...
writer.write(line);
writer.newLine(); // ...so add it back
}
}
}
static void attempt(String label, Callable action) {
try {
System.out.println(" " + label + ": " + action.call());
} catch (IOException e) {
System.out.println(" " + label + " -> " + e.getClass().getSimpleName());
}
}
interface Callable { Object call() throws IOException; }
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("weather");
try {
System.out.println("== 1. Low-level byte copies");
byte[] data = "ABCDEFGHIJ".getBytes(StandardCharsets.US_ASCII);
var one = new ByteArrayOutputStream();
copyByteByByte(new ByteArrayInputStream(data), one);
var good = new ByteArrayOutputStream();
copyInChunks(new ByteArrayInputStream(data), good, 4, false);
var bad = new ByteArrayOutputStream();
copyInChunks(new ByteArrayInputStream(data), bad, 4, true);
System.out.println(" byte by byte: " + one);
System.out.println(" 4-byte chunks: " + good);
System.out.println(" chunks, count ignored: " + bad + " (last chunk was only 2 bytes)");
System.out.println("\n== 2. Text files with BufferedReader / BufferedWriter");
File log = dir.resolve("station.log").toFile();
try (var w = new FileWriter(log, StandardCharsets.UTF_8)) { // creates or overwrites
w.write("INFO:sensor online\nWARN:wind 62 km/h\n");
}
try (var w = new FileWriter(log, StandardCharsets.UTF_8, true)) { // true = append
w.write("INFO:rain 4 mm\nWARN:hail expected\n");
}
File copy = dir.resolve("station-copy.log").toFile();
copyText(log, copy);
System.out.println(" copy has " + Files.readAllLines(copy.toPath()).size() + " lines, same bytes: "
+ (Files.mismatch(log.toPath(), copy.toPath()) == -1));
System.out.println("\n== 3. PrintWriter: print, println, printf, and no IOException");
File report = dir.resolve("report.txt").toFile();
try (var out = new PrintWriter(new BufferedWriter(new FileWriter(report, StandardCharsets.UTF_8)))) {
out.print("max temp: ");
out.println(31.5);
out.printf(Locale.ROOT, "humidity %d%%, pressure %.1f hPa%n", 64, 1013.25);
out.println(List.of("N", "NE")); // any object: String.valueOf()
System.out.println(" checkError() after writing: " + out.checkError());
}
System.out.print(Files.readString(report.toPath()).indent(2));
System.out.println("\n== 4. Files: whole-file helpers (everything in memory)");
Path p = dir.resolve("station.log");
String all = Files.readString(p);
byte[] bytes = Files.readAllBytes(p);
List<String> lines = Files.readAllLines(p);
System.out.println(" readString: " + all.length() + " chars, readAllBytes: " + bytes.length
+ " bytes, readAllLines: " + lines.size() + " lines");
Files.writeString(dir.resolve("a.txt"), all);
Files.write(dir.resolve("b.txt"), bytes);
Files.write(dir.resolve("c.txt"), lines); // adds a line separator after each line
System.out.println(" the three copies are identical: "
+ (Files.mismatch(dir.resolve("a.txt"), dir.resolve("b.txt")) == -1
&& Files.mismatch(dir.resolve("b.txt"), dir.resolve("c.txt")) == -1));
System.out.println("\n== 5. Files.lines(): lazy, stream-based, must be closed");
try (Stream<String> s = Files.lines(p)) {
s.filter(line -> line.startsWith("WARN:"))
.map(line -> line.substring(5))
.forEach(w -> System.out.println(" warning: " + w));
}
System.out.println("\n== 6. Files factories for I/O streams");
try (BufferedReader r = Files.newBufferedReader(p);
BufferedWriter w = Files.newBufferedWriter(dir.resolve("upper.log"))) {
String line;
while ((line = r.readLine()) != null) { w.write(line.toUpperCase()); w.newLine(); }
}
System.out.println(" newBufferedReader/Writer, first line: " + Files.readAllLines(dir.resolve("upper.log")).get(0));
try (InputStream in = Files.newInputStream(p);
OutputStream out = Files.newOutputStream(dir.resolve("raw.bin"))) {
System.out.println(" readNBytes(4): " + new String(in.readNBytes(4), StandardCharsets.UTF_8)
+ ", transferTo() copied the remaining " + in.transferTo(out) + " bytes");
}
System.out.println("\n== 7. Open options and errors");
Path notes = dir.resolve("notes.txt");
attempt("writeString(missing, APPEND)", () -> Files.writeString(notes, "a", StandardOpenOption.APPEND));
attempt("writeString(missing, CREATE, APPEND)", () -> Files.readString(
Files.writeString(notes, "cloudy", StandardOpenOption.CREATE, StandardOpenOption.APPEND)));
attempt("writeString(existing, APPEND)", () -> Files.readString(
Files.writeString(notes, " later", StandardOpenOption.APPEND)));
attempt("writeString(existing, CREATE_NEW)", () -> Files.writeString(notes, "x", StandardOpenOption.CREATE_NEW));
attempt("writeString(existing) with no options", () -> Files.readString(Files.writeString(notes, "clear")));
attempt("new FileReader(missing)", () -> new FileReader(dir.resolve("none.txt").toFile()));
attempt("Files.newBufferedReader(missing)", () -> Files.newBufferedReader(dir.resolve("none.txt")));
Files.write(dir.resolve("latin1.txt"), "Zoë".getBytes(StandardCharsets.ISO_8859_1));
attempt("Files.readString(ISO-8859-1 file)", () -> Files.readString(dir.resolve("latin1.txt")));
attempt("same file with the right charset", () -> Files.readString(dir.resolve("latin1.txt"), StandardCharsets.ISO_8859_1));
} finally {
try (Stream<Path> all = Files.walk(dir)) {
for (Path q : all.sorted(Comparator.reverseOrder()).toList()) Files.delete(q);
}
}
}
}
Output:
== 1. Low-level byte copies
byte by byte: ABCDEFGHIJ
4-byte chunks: ABCDEFGHIJ
chunks, count ignored: ABCDEFGHIJGH (last chunk was only 2 bytes)
== 2. Text files with BufferedReader / BufferedWriter
copy has 4 lines, same bytes: true
== 3. PrintWriter: print, println, printf, and no IOException
checkError() after writing: false
max temp: 31.5
humidity 64%, pressure 1013.3 hPa
[N, NE]
== 4. Files: whole-file helpers (everything in memory)
readString: 71 chars, readAllBytes: 71 bytes, readAllLines: 4 lines
the three copies are identical: true
== 5. Files.lines(): lazy, stream-based, must be closed
warning: wind 62 km/h
warning: hail expected
== 6. Files factories for I/O streams
newBufferedReader/Writer, first line: INFO:SENSOR ONLINE
readNBytes(4): INFO, transferTo() copied the remaining 67 bytes
== 7. Open options and errors
writeString(missing, APPEND) -> NoSuchFileException
writeString(missing, CREATE, APPEND): cloudy
writeString(existing, APPEND): cloudy later
writeString(existing, CREATE_NEW) -> FileAlreadyExistsException
writeString(existing) with no options: clear
new FileReader(missing) -> FileNotFoundException
Files.newBufferedReader(missing) -> NoSuchFileException
Files.readString(ISO-8859-1 file) -> MalformedInputException
same file with the right charset: Zoë
Points to notice:
- The buggy chunk copy produced
ABCDEFGHIJGH. The lastreadreturned 2, but all 4 buffer slots were written. - The second
FileWriterused the append flag, so the log had four lines, not two. printfwith%%printed a literal percent sign, andprintln(List.of(...))printed the list'stoString().- The three
Filescopies (writeString,writewith bytes,writewith lines) were byte-for-byte identical, because the log ended with a newline. APPENDon a missing file failed, whileCREATE, APPENDcreated it.- Reading an ISO-8859-1 file with the default UTF-8 threw
MalformedInputException, and passing the right charset fixed it.
Common questions
Files or I/O streams: which should I use?
For whole small files, the Files one-liners. For big files, use Files.lines() or a buffered stream from Files.newBufferedReader/newInputStream. Use java.io constructors when an API hands you a File or a stream.
Why does readLine() return null and not -1?
It returns a String, and -1 isn't a String. null is the "no more lines" signal for reference return types.
Do I need flush() before close()?
No. Closing flushes first. Call flush() explicitly only when data must reach its destination while the stream stays open, as with an interactive prompt or a log you want to survive a crash.
Summary
- I/O stream copy loops use
read()/write().readreturns-1at the end, and the array version returns the count, which you must respect when writing. BufferedReader.readLine()returns lines without terminators, andnullat the end.BufferedWriter.newLine()adds the separator.FileWriter/FileOutputStreamoverwrite unless the append flag istrue. Print streams never throwIOException.Files.readString,readAllBytesandreadAllLines(and theirwritepartners) work on whole files in memory.Files.lines()is lazy and must be closed.Fileswrite methods create or overwrite by default.APPEND,CREATEandCREATE_NEWchange that, and text defaults to UTF-8.
Practice quiz
Test yourself with the reading and writing files quiz: 10 exam-style questions with explanations.
Previous: Java I/O Streams: Byte and Character, Input and Output, Low-Level and High-Level (OCP 21)
Next: Java Serialization: Serializable, transient, serialVersionUID and Records (OCP 21)
Related reading
- Java I/O Streams: Byte and Character, Input and Output, Low-Level and High-Level (OCP 21)
- Java Parallel Streams: Parallel Decomposition, Reductions and Ordering (OCP 21)
- Java Collectors: joining, toMap, groupingBy, partitioningBy and teeing (OCP 21)
- Java Primitive Streams: IntStream, LongStream, DoubleStream and Summary Statistics (OCP 21)
- Java Stream Intermediate Operations: filter, map, flatMap, sorted, distinct, limit and peek (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.