Java I/O Streams: Byte, Character and Standard Streams
Files, network connections, keyboard input and even byte arrays in memory all produce or accept data. Java hides these differences behind one idea: the stream. Once you understand streams, reading a file and reading a web response look almost the same.
This tutorial explains what I/O streams are, the four stream families, how streams are chained and the standard streams every program has.
1. What Is a Stream in Java?
An I/O stream is an ordered flow of data between a program and a source or destination. The program processes the data piece by piece, in order, without needing all of it in memory at once.
Do not confuse I/O streams with the java.util.stream Stream API of Java 8, which processes collections of objects. They share a name but solve different problems.
2. Input Streams and Output Streams
- An input stream reads data into the program from a source, such as a file or the keyboard.
- An output stream writes data from the program to a destination, such as a file or the console.
A stream is one-way: you read from an input stream and write to an output stream.
3. The Four Stream Families
Every stream in java.io belongs to one of four families, each with an abstract base class:
Swipe sideways to see the whole diagram.
| Family | Base class | Unit of data | Typical use |
|---|---|---|---|
| Byte input | InputStream | 8-bit byte | Images, audio, ZIP files, any binary data |
| Byte output | OutputStream | 8-bit byte | Writing binary data |
| Character input | Reader | 16-bit char | Reading text |
| Character output | Writer | 16-bit char | Writing text |
Character streams translate between characters and bytes using a charset, so they are the right choice for text. The byte stream vs character stream tutorial compares them in detail.
4. Node Streams and Filter Streams
A node stream connects directly to a source or destination, such as FileInputStream or ByteArrayInputStream. A filter stream wraps another stream and adds a feature: buffering, compression, data types or character decoding. Because each wrapper is itself a stream, you can stack them:
BufferedReader -> InputStreamReader -> GZIPInputStream -> FileInputStream -> file
(lines) (bytes to chars) (decompress) (read bytes)
This is the decorator design pattern. Closing the outermost stream closes the whole chain.
5. Standard Streams: System.in, System.out and System.err
Every Java program starts with three ready-made streams in the System class:
| Field | Type | Connected to |
|---|---|---|
System.in | InputStream | Keyboard (standard input) |
System.out | PrintStream | Console output |
System.err | PrintStream | Error output, usually also the console |
You never close them yourself; the JVM manages them.
6. Example: Compressing Receipts with a Stream Chain
A billing system archives receipts as compressed text. Four streams work together, each doing one job.
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class ReceiptArchive {
public static void main(String[] args) throws IOException {
Path archive = Files.createTempFile("receipts", ".txt.gz");
// Writing: text -> characters to bytes -> compress -> buffer -> file
try (Writer out = new OutputStreamWriter(
new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(archive.toFile()))),
StandardCharsets.UTF_8)) {
for (int i = 1; i <= 500; i++) {
out.write("Receipt #" + i + ": paid in full\n");
}
}
// Reading: file -> decompress -> bytes to characters -> lines
long lines;
try (BufferedReader in = new BufferedReader(new InputStreamReader(
new GZIPInputStream(new FileInputStream(archive.toFile())), StandardCharsets.UTF_8))) {
System.out.println("First line: " + in.readLine());
lines = 1 + in.lines().count();
}
long textBytes = 0;
for (int i = 1; i <= 500; i++) {
textBytes += ("Receipt #" + i + ": paid in full\n").length();
}
System.out.println("Lines read back: " + lines);
System.out.println("Compressed file smaller than text: " + (Files.size(archive) < textBytes));
Files.delete(archive);
}
}
First line: Receipt #1: paid in full Lines read back: 500 Compressed file smaller than text: true
How the code works
- Writing:
OutputStreamWriterencodes text as UTF-8,GZIPOutputStreamcompresses the bytes,BufferedOutputStreamgroups them andFileOutputStreamwrites them to disk. - Reading reverses the chain:
GZIPInputStreamdecompresses andInputStreamReaderdecodes bytes back into characters. BufferedReader.lines()returns the remaining lines as a Java 8Stream, whichcount()totals.- Try-with-resources closes the outer stream, which closes every stream it wraps.
7. Example: Copying from Memory to a File
A weather service builds a CSV report in memory and saves it to a file. The copying code only works with InputStream and OutputStream, so it would work unchanged for any source or destination.
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class MemoryToFileCopy {
public static void main(String[] args) throws IOException {
byte[] csv = "city,temperature\nPune,31\nShimla,12\n".getBytes(StandardCharsets.UTF_8);
Path target = Files.createTempFile("weather", ".csv");
// The source is memory and the target is a file, but the code only sees two streams
try (InputStream in = new ByteArrayInputStream(csv);
OutputStream out = Files.newOutputStream(target)) {
long copied = in.transferTo(out); // Java 9: copies everything that is left
System.out.println("Bytes copied: " + copied);
}
System.out.println("File size: " + Files.size(target));
System.out.print(Files.readString(target));
Files.delete(target);
}
}
Bytes copied: 35 File size: 35 city,temperature Pune,31 Shimla,12
How the code works
ByteArrayInputStreamturns a byte array into an input stream, andFiles.newOutputStream()opens an output stream to the file.transferTo()(Java 9) copies all remaining bytes and returns how many it copied, replacing the classic read-and-write loop.- Both streams are declared in one try-with-resources statement and closed in reverse order.
8. Important Points
read()returns-1at the end of the stream; this is how a loop knows to stop.- Most stream methods throw
IOException, a checked exception. - Always close streams, ideally with try-with-resources, to release file handles.
- Buffered streams reduce slow system calls by reading and writing in larger chunks.
- Output streams may hold data in a buffer;
flush()pushes it out, andclose()flushes automatically.
9. Java Version Improvements and Java 25 Updates
| Java version | Change |
|---|---|
| Java 1.0 and 1.1 | Byte streams; then Reader and Writer for text. |
| Java 7 | Try-with-resources, and NIO.2 methods such as Files.newInputStream(). |
| Java 9 | InputStream.readAllBytes() and transferTo(). |
| Java 10 and 11 | Reader.transferTo(); nullInputStream(), nullOutputStream(), nullReader() and nullWriter(). |
| Java 18 | UTF-8 becomes the default charset (JEP 400). |
| Java 24 | Reader.of(CharSequence) reads directly from a String or other character sequence. |
| Java 25 | No new stream classes; java.lang.IO offers simple console input and output. |
10. Summary
- An I/O stream is a one-way, ordered flow of data to or from a program.
- There are four families:
InputStreamandOutputStreamfor bytes,ReaderandWriterfor text. - Node streams touch a source or destination; filter streams wrap them to add features.
System.in,System.outandSystem.errare always available.- Close streams with try-with-resources, and use
transferTo()to copy data.