00:00

Java I/O Streams: Byte, Character and Standard Streams

Last updated:

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:

The four Java I/O stream familiesFour groups. Byte input streams extend InputStream, for example FileInputStream, BufferedInputStream, ByteArrayInputStream, DataInputStream, ObjectInputStream and GZIPInputStream. Byte output streams extend OutputStream, for example FileOutputStream, BufferedOutputStream, ByteArrayOutputStream, DataOutputStream, PrintStream and GZIPOutputStream. Character input streams extend Reader, for example FileReader, BufferedReader, InputStreamReader, StringReader, CharArrayReader and PipedReader. Character output streams extend Writer, for example FileWriter, BufferedWriter, OutputStreamWriter, StringWriter, PrintWriter and CharArrayWriter.Byte inputInputStreamFileInputStreamBufferedInputStreamByteArrayInputStreamDataInputStreamObjectInputStreamGZIPInputStreamByte outputOutputStreamFileOutputStreamBufferedOutputStreamByteArrayOutputStreamDataOutputStreamPrintStreamGZIPOutputStreamCharacter inputReaderFileReaderBufferedReaderInputStreamReaderStringReaderCharArrayReaderPipedReaderCharacter outputWriterFileWriterBufferedWriterOutputStreamWriterStringWriterPrintWriterCharArrayWriter

Swipe sideways to see the whole diagram.

FamilyBase classUnit of dataTypical use
Byte inputInputStream8-bit byteImages, audio, ZIP files, any binary data
Byte outputOutputStream8-bit byteWriting binary data
Character inputReader16-bit charReading text
Character outputWriter16-bit charWriting 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:

Stream chain
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:

FieldTypeConnected to
System.inInputStreamKeyboard (standard input)
System.outPrintStreamConsole output
System.errPrintStreamError 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.

ReceiptArchive.java
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);
    }
}
Output
First line: Receipt #1: paid in full
Lines read back: 500
Compressed file smaller than text: true

How the code works

  1. Writing: OutputStreamWriter encodes text as UTF-8, GZIPOutputStream compresses the bytes, BufferedOutputStream groups them and FileOutputStream writes them to disk.
  2. Reading reverses the chain: GZIPInputStream decompresses and InputStreamReader decodes bytes back into characters.
  3. BufferedReader.lines() returns the remaining lines as a Java 8 Stream, which count() totals.
  4. 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.

MemoryToFileCopy.java
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);
    }
}
Output
Bytes copied: 35
File size:    35
city,temperature
Pune,31
Shimla,12

How the code works

  1. ByteArrayInputStream turns a byte array into an input stream, and Files.newOutputStream() opens an output stream to the file.
  2. transferTo() (Java 9) copies all remaining bytes and returns how many it copied, replacing the classic read-and-write loop.
  3. Both streams are declared in one try-with-resources statement and closed in reverse order.

8. Important Points

  • read() returns -1 at 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, and close() flushes automatically.

9. Java Version Improvements and Java 25 Updates

Java versionChange
Java 1.0 and 1.1Byte streams; then Reader and Writer for text.
Java 7Try-with-resources, and NIO.2 methods such as Files.newInputStream().
Java 9InputStream.readAllBytes() and transferTo().
Java 10 and 11Reader.transferTo(); nullInputStream(), nullOutputStream(), nullReader() and nullWriter().
Java 18UTF-8 becomes the default charset (JEP 400).
Java 24Reader.of(CharSequence) reads directly from a String or other character sequence.
Java 25No 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: InputStream and OutputStream for bytes, Reader and Writer for text.
  • Node streams touch a source or destination; filter streams wrap them to add features.
  • System.in, System.out and System.err are always available.
  • Close streams with try-with-resources, and use transferTo() to copy data.

Related Tutorials

11. Official Java Documentation References