Java OutputStream
The OutputStream Abstraction
java.io.OutputStream is the abstract base class for every destination of bytes in Java: files, network connections, HTTP responses, compressed archives, in-memory buffers. It is the mirror image of InputStream.
Code written against OutputStream can send its output anywhere. A method that writes a report, an image or a ZIP archive into an OutputStream can be pointed at a file, at an HTTP response that downloads it in the browser, or at a ByteArrayOutputStream in a unit test — without any change.
Subclasses must implement one method, write(int b); everything else has a default implementation.
| Method | Behaviour |
|---|---|
write(int b) | Writes one byte — the lowest 8 bits of b |
write(byte[] b) / write(byte[] b, int off, int len) | Writes all of b / len bytes starting at off |
flush() | Pushes any buffered bytes towards the final destination |
close() | Flushes, then releases the underlying resource. Further writes throw IOException |
OutputStream.nullOutputStream() (Java 11+) | A stream that discards everything written to it |
Unlike InputStream.read, write(byte[], off, len) always writes all the requested bytes before returning (or throws).
Common OutputStream Classes
| Class | Writes bytes to |
|---|---|
FileOutputStream, Files.newOutputStream(path) | A file |
ByteArrayOutputStream | A growing byte[] in memory |
socket.getOutputStream() | A TCP connection |
HttpServletResponse.getOutputStream() (servlets, Spring) | The body of an HTTP response |
System.out, System.err | Standard output/error (they are PrintStreams) |
Decorators, which wrap another OutputStream:
| Decorator | Adds |
|---|---|
BufferedOutputStream | A buffer that turns many small writes into few large ones |
PrintStream | Text output with print, println, printf (PrintStream lesson) |
DataOutputStream | Writing Java primitive types (Data Streams lesson) |
ObjectOutputStream | Serializing objects (Object Streams lesson) |
GZIPOutputStream, ZipOutputStream, DeflaterOutputStream | Compression |
CipherOutputStream | Encryption |
DigestOutputStream | Computing a hash of everything written |
ByteArrayOutputStream
ByteArrayOutputStream collects written bytes in memory. It's used whenever you need the output as a byte[] — to send it in a message, store it in a database column, compare it in a test, or measure it before writing it somewhere else.
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
public class O1 {
public static void main(String[] args) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
buffer.write('O');
buffer.write('K');
buffer.write(new byte[] {' ', '-', ' '});
buffer.write("Chennai ₹".getBytes(StandardCharsets.UTF_8));
System.out.println("size: " + buffer.size());
System.out.println("as text: " + buffer.toString(StandardCharsets.UTF_8));
byte[] copy = buffer.toByteArray();
System.out.println("first bytes: " + Arrays.toString(Arrays.copyOf(copy, 5)));
ByteArrayOutputStream file = new ByteArrayOutputStream();
buffer.writeTo(file);
buffer.reset();
System.out.println("after reset: size " + buffer.size() + ", copy still has " + file.size() + " bytes");
OutputStream discard = OutputStream.nullOutputStream();
discard.write(new byte[1_000_000]);
System.out.println("nullOutputStream accepted 1,000,000 bytes and kept none");
}
}
Output:
size: 16
as text: OK - Chennai ₹
first bytes: [79, 75, 32, 45, 32]
after reset: size 0, copy still has 16 bytes
nullOutputStream accepted 1,000,000 bytes and kept none
- The internal array grows automatically.
size()is the number of bytes written so far: 5 ASCII bytes plus 11 bytes forChennai ₹(8 ASCII characters and 3 bytes for₹). toString(Charset)(Java 10+) decodes the content as text;toByteArray()returns a copy of the bytes.writeTo(OutputStream)copies the whole content to another stream;reset()empties the buffer so it can be reused, without affecting copies already taken.- Closing a
ByteArrayOutputStreamhas no effect, and its methods never actually fail, but they're declared withthrows IOExceptionwhere inherited fromOutputStream, so compile-time handling is still required. nullOutputStream()is useful when an API requires an output stream but you don't need the output — for instance, to compute a checksum through aDigestOutputStreamwithout storing the data.
Everything lives in memory, so a ByteArrayOutputStream isn't suitable for very large outputs (and a single one can't exceed about 2 GB, the maximum array size).
flush and close in Layered Streams
When streams are layered, each layer may hold data that hasn't been passed on yet. Two rules follow:
- Close the outermost stream. Its
close()flushes its own buffered data into the next layer and closes that layer, and so on down to the file or socket. flush()isn't always enough. It pushes buffered bytes onward, but some decorators can only complete their output when they know the data has ended.
Compression shows the second rule clearly:
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.zip.*;
public class Gzip {
static byte[] compress(String text, boolean close) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
GZIPOutputStream gz = new GZIPOutputStream(bytes);
gz.write(text.getBytes(StandardCharsets.UTF_8));
gz.flush();
if (close) gz.close();
return bytes.toByteArray();
}
static String decompress(byte[] data) throws IOException {
try (InputStream in = new GZIPInputStream(new ByteArrayInputStream(data))) {
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
}
}
public static void main(String[] args) throws IOException {
String text = "order shipped\n".repeat(100);
byte[] closed = compress(text, true);
System.out.println("closed: " + closed.length + " bytes, round trip ok: " + decompress(closed).equals(text));
byte[] notClosed = compress(text, false);
System.out.println("not closed: " + notClosed.length + " bytes");
try {
decompress(notClosed);
} catch (EOFException e) {
System.out.println("decompress failed: EOFException " + e.getMessage());
}
}
}
Output:
closed: 46 bytes, round trip ok: true
not closed: 10 bytes
decompress failed: EOFException Unexpected end of ZLIB input stream
- When the
GZIPOutputStreamis closed, it writes the remaining compressed data and the GZIP trailer (a checksum and the original length). The 1,400 bytes of text become 46 bytes and decompress correctly. - Without
close(), only the 10-byte GZIP header was produced. The compressor still holds the data, waiting for more input —flush()doesn't force it out (unless the stream was created withsyncFlush = true). The result is a corrupt file that fails withEOFException. - If the destination must stay open (for example, a socket you'll keep using), call
finish()instead ofclose(): it completes the compressed output without closing the underlying stream.ZipOutputStreamandDeflaterOutputStreamwork the same way.
The general lesson: a missing close() doesn't always cause an obvious error — sometimes it silently produces a truncated or invalid file. try-with-resources prevents the whole class of bugs.
Writing Your Own OutputStream
Like InputStream, an OutputStream subclass only needs write(int), and should override write(byte[], int, int) for performance. To decorate another stream, extend FilterOutputStream, which stores the wrapped stream in the field out:
static class CountingOutputStream extends FilterOutputStream {
long count = 0;
CountingOutputStream(OutputStream out) { super(out); }
@Override public void write(int b) throws IOException { out.write(b); count++; }
@Override public void write(byte[] b, int off, int len) throws IOException { out.write(b, off, len); count += len; }
}
Overriding the array version matters for a second reason here: FilterOutputStream.write(byte[], int, int) by default calls write(int) once per byte, which would be very slow. Calling out.write(b, off, len) passes the whole block through in one call.
Practical Example: Exporting Reports as a ZIP Archive
An admin dashboard offers "download all monthly reports" as one ZIP file and shows the file's size and SHA-256 checksum, so the download can be verified. Rather than writing the ZIP and then reading it back twice (once to measure, once to hash), the output passes through decorators that measure and hash it while it's being written.
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.security.*;
import java.util.*;
import java.util.zip.*;
public class Zip {
static class CountingOutputStream extends FilterOutputStream {
long count = 0;
CountingOutputStream(OutputStream out) { super(out); }
@Override public void write(int b) throws IOException { out.write(b); count++; }
@Override public void write(byte[] b, int off, int len) throws IOException { out.write(b, off, len); count += len; }
}
record Export(Path file, long bytes, String sha256) { }
static Export exportReports(Map<String, String> reports, Path target) throws IOException, NoSuchAlgorithmException {
MessageDigest sha = MessageDigest.getInstance("SHA-256");
CountingOutputStream counter;
try (OutputStream file = Files.newOutputStream(target);
DigestOutputStream digest = new DigestOutputStream(new BufferedOutputStream(file), sha);
ZipOutputStream zip = new ZipOutputStream(counter = new CountingOutputStream(digest), StandardCharsets.UTF_8)) {
for (Map.Entry<String, String> r : reports.entrySet()) {
zip.putNextEntry(new ZipEntry("reports/" + r.getKey()));
zip.write(r.getValue().getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
}
return new Export(target, counter.count, HexFormat.of().formatHex(sha.digest()));
}
public static void main(String[] args) throws Exception {
Map<String, String> reports = new LinkedHashMap<>();
reports.put("sales-2026-11.csv", "course,revenue\nJava,48250\nDjango,31900\n".repeat(50));
reports.put("signups-2026-11.csv", "date,count\n2026-11-01,42\n2026-11-02,57\n".repeat(50));
reports.put("summary.txt", "Total revenue: 80150 INR\n");
Export e = exportReports(reports, Path.of("reports-2026-11.zip"));
System.out.println("written " + e.bytes() + " bytes, file size " + Files.size(e.file()));
System.out.println("sha256 matches file: " + e.sha256().equals(sha256(e.file())));
try (ZipFile zf = new ZipFile(e.file().toFile())) {
zf.stream().forEach(entry -> System.out.printf(" %-28s %5d -> %4d bytes%n",
entry.getName(), entry.getSize(), entry.getCompressedSize()));
}
}
static String sha256(Path p) throws Exception {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(p)));
}
}
Output:
written 577 bytes, file size 577
sha256 matches file: true
reports/sales-2026-11.csv 1950 -> 59 bytes
reports/signups-2026-11.csv 1950 -> 51 bytes
reports/summary.txt 25 -> 27 bytes
The chain of streams, from the code's point of view down to the disk:
ZipOutputStream → CountingOutputStream → DigestOutputStream → BufferedOutputStream → file
(compresses) (counts bytes) (updates SHA-256) (batches writes)
Step by step:
- Building the chain in try-with-resources. Each resource wraps the previous one. They're closed in reverse order: the
ZipOutputStreamfirst — which writes its final data, the archive's central directory — then the digest stream, which flushes the buffer, then the file. If the ZIP stream weren't closed (orfinish()ed), the archive would have no central directory and most tools would report it as corrupt. - Assigning in an expression.
counter = new CountingOutputStream(digest)stores the counter in a variable while passing it to theZipOutputStreamconstructor, so its count can be read after thetryblock, when all bytes have been written. - Writing entries. For each report,
putNextEntrystarts a file inside the archive,writeprovides its content (compressed on the fly), andcloseEntrycompletes it. Thereports/prefix creates a folder inside the ZIP. PassingStandardCharsets.UTF_8makes entry names with non-ASCII characters portable. - Measuring and hashing for free. Every compressed byte passes through the counter and the digest on its way to the file, so the final count (577) equals the file size, and the SHA-256 computed during writing equals a hash computed by reading the finished file afterwards.
- Verification.
ZipFilereads the archive back and lists each entry with its original and compressed size. The repetitive CSV reports shrink dramatically; the tiny summary grows slightly (25 → 27 bytes), because compression has a small fixed overhead. Many ZIP tools store such tiny files uncompressed for that reason; withZipOutputStreamyou can do the same by callingentry.setMethod(ZipEntry.STORED), which also requires setting the entry's size and CRC-32 checksum in advance.
Because exportReports writes to an OutputStream chain that starts at a file, changing one line — passing response.getOutputStream() instead of Files.newOutputStream(target) — would stream the same ZIP directly to a user's browser, without creating a file on the server at all.