00:00

OutputStream Class in Java: Methods and Examples

Last updated:

Saving an image, sending a response over the network and building a PDF in memory all mean writing bytes somewhere. In Java, every byte destination is represented by one abstract class: java.io.OutputStream.

This tutorial explains OutputStream, its subclasses and methods, and shows how to write code that works with any destination and how to create your own output stream.

1. What Is OutputStream in Java?

OutputStream is the abstract superclass of all classes that write bytes. It has been in Java since version 1.0 and implements Closeable and Flushable, so it can be used in try-with-resources and flushed on demand.

Its only abstract method is write(int b), which writes the lowest 8 bits of b as one byte. The array versions call it by default, and subclasses usually override them for speed.

Declaration
public abstract class OutputStream implements Closeable, Flushable

2. OutputStream Class Hierarchy

OutputStream hierarchy and methodsLeft: OutputStream, an abstract class that implements Closeable and Flushable, with subclasses FileOutputStream, ByteArrayOutputStream, FilterOutputStream (extended by BufferedOutputStream, DataOutputStream and PrintStream), ObjectOutputStream and PipedOutputStream. Right: its methods grouped as write (the abstract write(int), write(byte[]) and write(byte[], off, len)), finish (flush and close) and the Java 11 factory nullOutputStream.OutputStreamabstract class, implements Closeable, FlushableFileOutputStreama fileByteArrayOutputStreama byte[]FilterOutputStreamwrappersBufferedOutputStreambufferingDataOutputStreamprimitivesPrintStreamformattedObjectOutputStreamobjectsPipedOutputStreamthreadsWritewrite(int) abstract, one bytewrite(byte[])write(byte[], off, len)Finishflush() push buffered bytes outclose() flush and releaseFactorynullOutputStream() Java 11

Swipe sideways to see the whole diagram.

3. Methods of the OutputStream Class

MethodDescription
write(int b)Writes one byte (the low 8 bits of b). Abstract.
write(byte[] b)Writes the whole array.
write(byte[] b, int off, int len)Writes len bytes starting at index off.
flush()Forces any buffered bytes to be written to the destination.
close()Releases the resource; a closed stream cannot be reused.
nullOutputStream()A static factory for a stream that discards all bytes (Java 11).

4. Example: One Method for Every Destination

A shop prints receipts. The same writeReceipt() method writes to memory, for a preview, and to a file, for the archive, because it only depends on OutputStream.

ReceiptPrinter.java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class ReceiptPrinter {

    // Writes to ANY OutputStream: memory, file, printer, socket ...
    static void writeReceipt(OutputStream out, String item, int paise) throws IOException {
        out.write(("ITEM " + item + "\n").getBytes(StandardCharsets.UTF_8));
        out.write(("TOTAL " + paise / 100 + "." + String.format("%02d", paise % 100) + "\n").getBytes(StandardCharsets.UTF_8));
        out.flush();
    }

    public static void main(String[] args) throws IOException {
        ByteArrayOutputStream memory = new ByteArrayOutputStream();
        writeReceipt(memory, "Notebook", 14950);

        Path file = Files.createTempFile("receipt", ".txt");
        try (OutputStream out = Files.newOutputStream(file)) {
            writeReceipt(out, "Notebook", 14950);
        }

        System.out.print(memory.toString(StandardCharsets.UTF_8));
        System.out.println("Bytes in memory: " + memory.size() + ", bytes in file: " + Files.size(file));
        Files.delete(file);
    }
}
Output
ITEM Notebook
TOTAL 149.50
Bytes in memory: 27, bytes in file: 27

How the code works

  1. writeReceipt() turns text into UTF-8 bytes and writes them with write(byte[]).
  2. ByteArrayOutputStream collects the bytes in memory, and toString(StandardCharsets.UTF_8) (Java 10) turns them back into text.
  3. Files.newOutputStream() writes the same bytes to a file, so both destinations hold 27 bytes.

5. Example: Writing Your Own OutputStream

A reporting tool needs to know how large a report will be before saving it. A tiny custom OutputStream counts bytes as they pass through, and nullOutputStream() throws them away.

ByteCounter.java
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

public class ByteCounter extends OutputStream {
    private final OutputStream target;
    private long count;

    ByteCounter(OutputStream target) {
        this.target = target;
    }

    @Override
    public void write(int b) throws IOException {      // the only abstract method
        target.write(b);
        count++;
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        target.write(b, off, len);                     // pass the whole array on at once
        count += len;
    }

    long count() {
        return count;
    }

    public static void main(String[] args) throws IOException {
        String report = "Monthly sales: 1,24,500 units\n".repeat(1000);

        // nullOutputStream() (Java 11) discards everything: we only want the size
        try (ByteCounter counter = new ByteCounter(OutputStream.nullOutputStream())) {
            counter.write(report.getBytes(StandardCharsets.UTF_8));
            counter.write('\n');
            System.out.println("Report size: " + counter.count() + " bytes");
        }
    }
}
Output
Report size: 30001 bytes

How the code works

  1. ByteCounter extends OutputStream and implements the abstract write(int).
  2. It also overrides write(byte[], int, int) to pass the array on in one call, because the inherited version would call write(int) once per byte.
  3. OutputStream.nullOutputStream() (Java 11) accepts and discards every byte, so nothing is stored.
  4. The 1,000 report lines plus one newline add up to 30,001 bytes.

6. Important Points

  • Writing to a closed stream throws an IOException.
  • close() calls flush() first in most implementations, including BufferedOutputStream.
  • flush() hands bytes to the operating system; it does not guarantee that they are physically on the disk.
  • A method that accepts an OutputStream should normally not close it; the code that opened the stream closes it.

7. Common Mistakes and Best Practices

  • Forgetting to close or flush. Buffered bytes are lost; use try-with-resources.
  • Overriding only write(int) in a subclass. It works, but is slow for arrays; also override write(byte[], int, int).
  • Writing text with getBytes() and no charset. Pass StandardCharsets.UTF_8 so the bytes are predictable.
  • Using OutputStream for text everywhere. For text, a Writer handles encoding for you.

8. Java Version Improvements and Java 25 Updates

Java versionChange
Java 1.0OutputStream with write(), flush() and close().
Java 5Implements Closeable and Flushable.
Java 7Usable in try-with-resources through AutoCloseable.
Java 11OutputStream.nullOutputStream().
Java 25No new methods; the API above is current.

9. Summary

  • OutputStream is the abstract base class of every byte output stream.
  • Subclasses must implement write(int) and should override the array version.
  • Code that accepts an OutputStream can write to files, memory, sockets and more.
  • Flush or close streams so buffered data reaches its destination.
  • nullOutputStream() is handy for measuring or discarding output.

Related Tutorials

10. Official Java Documentation References