Java I/O Streams: Byte and Character, Input and Output, Low-Level and High-Level (OCP 21)
The java.io stream family for the OCP 21 exam: byte versus character streams, character encodings and Charset, input versus output, low-level versus high-level streams and wrapping, the four abstract base classes, legal and illegal combinations, and decoding class names.
kvi5hnuCode Sprout team member8 min readOn this page
Path and Files locate and manage files. To process a file's contents piece by piece, Java uses I/O streams from java.io. An I/O stream is a sequence of data that you read or write in order, with only a small part in memory at a time. That's how a program with little memory can process a file of many gigabytes.
The java.io package has dozens of classes, but their names follow a system. Once you can decode a name, you know what the class does. This article is about that system. Article 88 covers using the classes to read and write files.
Byte streams and character streams
Everything on disk is bits grouped into bytes. Java has two families of I/O streams:
| Byte streams | Character streams | |
|---|---|---|
| Data | raw bytes: images, audio, any binary file | text: char and String |
| Name ends in | InputStream / OutputStream | Reader / Writer |
| Example | FileInputStream | FileReader |
A Reader or Writer is still an I/O stream, even though "Stream" isn't in its name. In this chapter, "input stream" means an InputStream or a Reader, and "output stream" means an OutputStream or a Writer.
Character encodings
A character stream converts between characters and bytes using a character encoding, or charset. Different charsets use different numbers of bytes:
| Charset | Bytes for "café ☕" (6 chars) | Notes |
|---|---|---|
US-ASCII | 6, but é and ☕ become ? | 7-bit English only |
ISO-8859-1 | 6, but ☕ becomes ? | one byte per character, Western European |
UTF-8 | 9 | 1 to 4 bytes per character, the web standard |
UTF-16 | 12, plus a 2-byte marker with plain UTF-16 | 2 or 4 bytes per character |
In Java, a charset is a java.nio.charset.Charset:
Charset utf8 = Charset.forName("UTF-8"); // by name, case-insensitive
Charset same = StandardCharsets.UTF_8; // constant, no lookup, no typos
Reading bytes with the wrong charset corrupts the text. "café" written as UTF-8 and read as ISO-8859-1 becomes "café". You don't need to memorize charsets for the exam, but you should recognize the names.
Input and output
Most input classes have a matching output class: FileInputStream/FileOutputStream, FileReader/FileWriter, BufferedReader/BufferedWriter. Data written by one can be read by the other.
The exam's favorite exceptions:
PrintStreamis anOutputStreamwith no input partner. It also doesn't have "Output" in its name.System.outandSystem.errarePrintStreams.PrintWriteris aWriterwith noPrintReader.
Low-level and high-level streams
- A low-level stream connects directly to the data source, such as a file, a byte array or a
String. For the exam, the low-level classes to know are the file ones:FileInputStream,FileOutputStream,FileReaderandFileWriter. - A high-level stream wraps another stream: you pass the other stream to its constructor. It adds features, such as buffering, reading whole lines, reading objects or printing formatted text, and passes the work down to the stream it wraps.
try (var reader = new BufferedReader(new FileReader("menu.txt"))) { // high wraps low
System.out.println(reader.readLine()); // a high-level extra
}
High-level streams can wrap other high-level streams. Each layer adds something:
try (var in = new ObjectInputStream( // reads Java objects and primitives
new BufferedInputStream( // reads the file in efficient chunks
new FileInputStream("order.bin")))) { // the only layer that touches the file
System.out.println(in.readObject());
}

Closing the outermost stream closes the whole chain, and a buffered output stream is flushed first. You only need to put the outer stream in try-with-resources.
The four abstract base classes
| Abstract class | Parent of all |
|---|---|
InputStream | byte input streams |
OutputStream | byte output streams |
Reader | character input streams |
Writer | character output streams |
They're abstract, so new InputStream() doesn't compile. A high-level stream's constructor usually takes one of these types. BufferedWriter(Writer out), for example, accepts any Writer, but only a Writer.
Combinations that don't compile
The exam likes to mix up families and directions:
new BufferedInputStream(new FileReader("z.txt")); // DOES NOT COMPILE: Reader isn't an InputStream
new BufferedWriter(new FileOutputStream("z.txt")); // DOES NOT COMPILE: OutputStream isn't a Writer
new ObjectInputStream(new FileOutputStream("z.txt")); // DOES NOT COMPILE: output where input is needed
new BufferedInputStream(new InputStream()); // DOES NOT COMPILE: abstract class
new BufferedReader("z.txt"); // DOES NOT COMPILE: needs a Reader, not a file name
new PrintStream(new FileWriter("z.txt")); // DOES NOT COMPILE: PrintStream wraps OutputStreams
To move data from an input stream to an output stream, you copy it (article 88). You don't wrap one in the other.
The bridges
Two classes deliberately cross between the families. Their names contain both:
InputStreamReaderis aReaderthat wraps anInputStream, decoding bytes into characters with a charset.OutputStreamWriteris aWriterthat wraps anOutputStream, encoding characters into bytes.
PrintWriter is also flexible. It accepts a Writer, an OutputStream, a file name or a File.
Classes to know
| Class | Level | What it does |
|---|---|---|
FileInputStream | low | reads bytes from a file |
FileOutputStream | low | writes bytes to a file |
FileReader | low | reads characters from a file |
FileWriter | low | writes characters to a file |
BufferedInputStream | high | reads bytes from an InputStream in chunks for speed |
BufferedOutputStream | high | writes bytes to an OutputStream in chunks |
BufferedReader | high | buffered characters, plus readLine() |
BufferedWriter | high | buffered characters, plus newLine() |
ObjectInputStream | high | reads primitives and serialized objects |
ObjectOutputStream | high | writes primitives and serialized objects |
PrintStream | high | writes formatted text to a byte stream (System.out) |
PrintWriter | high | writes formatted text to a character stream |
When a question shows a class you don't recognize, decode its name: ObjectOutputStream writes objects as bytes, and FileReader reads characters from a file.
Why read() returns an int
InputStream.read() returns the next byte as an int from 0 to 255, and Reader.read() returns the next character as an int from 0 to 65,535. Both return -1 at the end of the stream. A byte can't hold 256 different data values plus an end marker, so the return type is the larger int. A byte with value -1 (0xFF) is returned as 255, so it can't be confused with the end.
What's current
- Java 18 (JEP 400): the default charset is UTF-8 on every platform. Before Java 18 it depended on the operating system, so the same program could read text differently on Windows and Linux. You can still pass a charset explicitly, and that's good practice.
- Java 10/11:
FileReader,FileWriterandPrintWritergained constructors that take aCharset. Earlier code had to useInputStreamReader/OutputStreamWriterto choose an encoding. - Java 9 and later added
InputStream.readAllBytes(),readNBytes()andtransferTo(), which article 88 uses. - Low-level stream classes still don't accept a
Path. Usepath.toFile(), or theFiles.newInputStream/newBufferedReaderfactories (article 88).
Exam traps from this article
A complete example
A café's ordering system writes and reads data with many kinds of streams. The program compares how four charsets encode the same text, shows mojibake from a charset mismatch, and classifies ten classes by family. It demonstrates read() returning 255 for a -1 byte, round-trips text and objects through wrapped file streams, uses both bridges and both kinds of PrintWriter, and shows that closing the top of a chain closes the bottom.
import java.io.*;
import java.nio.charset.*;
import java.nio.file.*;
import java.util.*;
public class Solution {
/** A byte sink that reports when it is closed, so we can watch close() pass down a chain. */
static class LoudSink extends ByteArrayOutputStream {
@Override
public void close() throws IOException {
System.out.println(" LoudSink.close() called");
super.close();
}
}
static String family(Class<?> c) {
if (InputStream.class.isAssignableFrom(c)) return "InputStream (bytes in)";
if (OutputStream.class.isAssignableFrom(c)) return "OutputStream (bytes out)";
if (Reader.class.isAssignableFrom(c)) return "Reader (chars in)";
if (Writer.class.isAssignableFrom(c)) return "Writer (chars out)";
return "?";
}
public static void main(String[] args) throws IOException {
System.out.println("== 1. Characters are stored as bytes; the charset decides how");
String word = "café ☕";
System.out.println(" \"" + word + "\" has " + word.length() + " chars");
for (Charset cs : List.of(StandardCharsets.US_ASCII, StandardCharsets.ISO_8859_1,
StandardCharsets.UTF_8, StandardCharsets.UTF_16BE)) {
byte[] bytes = word.getBytes(cs);
System.out.println(" " + cs.name() + ": " + bytes.length + " bytes, decodes back to \"" + new String(bytes, cs) + "\"");
}
System.out.println(" Charset.forName(\"utf-8\") is UTF_8: " + Charset.forName("utf-8").equals(StandardCharsets.UTF_8));
System.out.println(" default charset (UTF-8 since Java 18): " + Charset.defaultCharset());
byte[] utf8 = "café".getBytes(StandardCharsets.UTF_8);
System.out.println(" UTF-8 bytes decoded as ISO-8859-1: \"" + new String(utf8, StandardCharsets.ISO_8859_1) + "\"");
System.out.println("\n== 2. Four abstract base classes; the name tells you the family");
for (Class<?> c : List.of(FileInputStream.class, BufferedOutputStream.class, ObjectInputStream.class,
PrintStream.class, FileReader.class, BufferedReader.class, InputStreamReader.class,
FileWriter.class, PrintWriter.class, OutputStreamWriter.class))
System.out.printf(" %-20s %s%n", c.getSimpleName(), family(c));
System.out.println(" System.out is a " + System.out.getClass().getSimpleName());
System.out.println("\n== 3. read() returns an int so that -1 can mean 'end of stream'");
InputStream in = new ByteArrayInputStream(new byte[] {65, -1, 0});
int b;
StringBuilder sb = new StringBuilder();
while ((b = in.read()) != -1) sb.append(b).append(' ');
System.out.println(" bytes {65, -1, 0} read as: " + sb.toString().trim() + ", then -1");
Path tmp = Files.createTempDirectory("io");
try {
System.out.println("\n== 4. Low-level streams talk to the file; high-level streams wrap them");
Path text = tmp.resolve("menu.txt");
try (var out = new BufferedWriter(new FileWriter(text.toFile(), StandardCharsets.UTF_8))) {
out.write("soup of the day");
out.newLine(); // high-level extra
out.write("crème brûlée");
}
try (var reader = new BufferedReader(new FileReader(text.toFile(), StandardCharsets.UTF_8))) {
System.out.println(" readLine() #1: " + reader.readLine());
System.out.println(" readLine() #2: " + reader.readLine());
System.out.println(" readLine() #3: " + reader.readLine());
}
System.out.println(" file size: " + Files.size(text) + " bytes for "
+ "soup of the day\ncrème brûlée".length() + " chars (é, è and û take 2 bytes each)");
System.out.println("\n== 5. Chains can be several layers deep");
Path data = tmp.resolve("order.bin");
try (var out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(data.toFile())))) {
out.writeInt(42);
out.writeUTF("table 7");
out.writeObject(List.of("tea", "scone"));
}
try (var in2 = new ObjectInputStream(new BufferedInputStream(new FileInputStream(data.toFile())))) {
System.out.println(" readInt(): " + in2.readInt() + ", readUTF(): " + in2.readUTF()
+ ", readObject(): " + in2.readObject());
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
}
System.out.println("\n== 6. Bridges between bytes and characters");
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
try (Writer w = new OutputStreamWriter(bytesOut, StandardCharsets.UTF_16BE)) {
w.write("hi");
}
System.out.println(" OutputStreamWriter (UTF-16BE) turned \"hi\" into bytes " + Arrays.toString(bytesOut.toByteArray()));
try (Reader r = new InputStreamReader(new ByteArrayInputStream(bytesOut.toByteArray()), StandardCharsets.UTF_16BE)) {
System.out.println(" InputStreamReader read them back as: " + (char) r.read() + (char) r.read());
}
StringWriter sw = new StringWriter();
try (var pw = new PrintWriter(sw)) { // PrintWriter wraps a Writer...
pw.printf(Locale.ROOT, "%s costs %.2f%n", "tea", 2.5);
}
ByteArrayOutputStream raw = new ByteArrayOutputStream();
try (var pw = new PrintWriter(raw, true, StandardCharsets.UTF_8)) { // ...or an OutputStream
pw.print("scone");
}
System.out.print(" PrintWriter over a Writer: " + sw);
System.out.println(" PrintWriter over an OutputStream: " + raw.toString(StandardCharsets.UTF_8));
System.out.println("\n== 7. Closing the outermost stream closes the whole chain");
LoudSink sink = new LoudSink();
try (var top = new PrintStream(new BufferedOutputStream(sink), false, StandardCharsets.UTF_8)) {
top.print("bye");
}
System.out.println(" close() flushed the buffer first, the sink holds: " + sink.toString(StandardCharsets.UTF_8));
} finally {
for (String f : List.of("menu.txt", "order.bin")) Files.deleteIfExists(tmp.resolve(f));
Files.delete(tmp);
}
}
}
Output:
== 1. Characters are stored as bytes; the charset decides how
"café ☕" has 6 chars
US-ASCII: 6 bytes, decodes back to "caf? ?"
ISO-8859-1: 6 bytes, decodes back to "café ?"
UTF-8: 9 bytes, decodes back to "café ☕"
UTF-16BE: 12 bytes, decodes back to "café ☕"
Charset.forName("utf-8") is UTF_8: true
default charset (UTF-8 since Java 18): UTF-8
UTF-8 bytes decoded as ISO-8859-1: "café"
== 2. Four abstract base classes; the name tells you the family
FileInputStream InputStream (bytes in)
BufferedOutputStream OutputStream (bytes out)
ObjectInputStream InputStream (bytes in)
PrintStream OutputStream (bytes out)
FileReader Reader (chars in)
BufferedReader Reader (chars in)
InputStreamReader Reader (chars in)
FileWriter Writer (chars out)
PrintWriter Writer (chars out)
OutputStreamWriter Writer (chars out)
System.out is a PrintStream
== 3. read() returns an int so that -1 can mean 'end of stream'
bytes {65, -1, 0} read as: 65 255 0, then -1
== 4. Low-level streams talk to the file; high-level streams wrap them
readLine() #1: soup of the day
readLine() #2: crème brûlée
readLine() #3: null
file size: 31 bytes for 28 chars (é, è and û take 2 bytes each)
== 5. Chains can be several layers deep
readInt(): 42, readUTF(): table 7, readObject(): [tea, scone]
== 6. Bridges between bytes and characters
OutputStreamWriter (UTF-16BE) turned "hi" into bytes [0, 104, 0, 105]
InputStreamReader read them back as: hi
PrintWriter over a Writer: tea costs 2.50
PrintWriter over an OutputStream: scone
== 7. Closing the outermost stream closes the whole chain
LoudSink.close() called
close() flushed the buffer first, the sink holds: bye
Points to notice:
"café ☕"took 6, 6, 9 and 12 bytes in different charsets, and only the Unicode charsets brought it back unchanged.- The UTF-8 bytes of
cafédecoded as ISO-8859-1 becamecafé. That's what a charset mismatch looks like. - The byte
-1was read as255, and only the real end of the stream returned-1. readLine()returnednullafter the last line. That's howBufferedReadersignals the end.- The file held 31 bytes for 28 characters, because UTF-8 needs two bytes for
è,ûandé. - Closing the outer
PrintStreamflushed the buffer and closed the sink at the bottom of the chain.
Common questions
When should I use a byte stream instead of a character stream? Use byte streams for anything that isn't text, such as images, archives and serialized objects, or when you must preserve the exact bytes. Use character streams for text, ideally with an explicit charset.
Do I have to close every stream in a chain? No. Close the outermost one, and it closes the rest. Putting just the outer stream in try-with-resources is enough.
Is ByteArrayInputStream low-level?
Technically yes, because it reads from memory directly. The exam only asks about the file streams as low-level examples.
Summary
java.iohas byte streams (InputStream/OutputStream) and character streams (Reader/Writer). Character streams use aCharsetto convert to and from bytes.- Input and output classes usually come in pairs, except
PrintStreamandPrintWriter. - Low-level streams touch the data source, and high-level streams wrap other streams of the same family and direction to add features.
- The four abstract base classes define the families. The bridges
InputStreamReaderandOutputStreamWriterconvert between them. read()returns anint, with-1at the end of the stream. Closing the outer stream closes the chain.
Practice quiz
Test yourself with the I/O streams quiz: 10 exam-style questions with explanations.
Previous: Java Files: Copying, Moving, Deleting and Comparing Files (OCP 21)
Next: Java Reading and Writing Files: I/O Streams, Buffered Readers and Files Methods (OCP 21)
Related reading
- 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)
- Java Stream Terminal Operations: count, min, max, find, match, forEach, reduce and collect (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.