OutputStream Class in Java: Methods and Examples
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.
public abstract class OutputStream implements Closeable, Flushable
2. OutputStream Class Hierarchy
Swipe sideways to see the whole diagram.
3. Methods of the OutputStream Class
| Method | Description |
|---|---|
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.
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);
}
}
ITEM Notebook TOTAL 149.50 Bytes in memory: 27, bytes in file: 27
How the code works
writeReceipt()turns text into UTF-8 bytes and writes them withwrite(byte[]).ByteArrayOutputStreamcollects the bytes in memory, andtoString(StandardCharsets.UTF_8)(Java 10) turns them back into text.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.
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");
}
}
}
Report size: 30001 bytes
How the code works
ByteCounterextendsOutputStreamand implements the abstractwrite(int).- It also overrides
write(byte[], int, int)to pass the array on in one call, because the inherited version would callwrite(int)once per byte. OutputStream.nullOutputStream()(Java 11) accepts and discards every byte, so nothing is stored.- 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()callsflush()first in most implementations, includingBufferedOutputStream.flush()hands bytes to the operating system; it does not guarantee that they are physically on the disk.- A method that accepts an
OutputStreamshould 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 overridewrite(byte[], int, int). - Writing text with
getBytes()and no charset. PassStandardCharsets.UTF_8so the bytes are predictable. - Using
OutputStreamfor text everywhere. For text, aWriterhandles encoding for you.
8. Java Version Improvements and Java 25 Updates
| Java version | Change |
|---|---|
| Java 1.0 | OutputStream with write(), flush() and close(). |
| Java 5 | Implements Closeable and Flushable. |
| Java 7 | Usable in try-with-resources through AutoCloseable. |
| Java 11 | OutputStream.nullOutputStream(). |
| Java 25 | No new methods; the API above is current. |
9. Summary
OutputStreamis the abstract base class of every byte output stream.- Subclasses must implement
write(int)and should override the array version. - Code that accepts an
OutputStreamcan 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
- InputStream Class in Java
- FileOutputStream Class in Java
- BufferedOutputStream Class in Java
- Byte Stream in Java