Java OutputStream

Su Suriya Ravichandran Updated 18 Nov 2026
9 min read ·Lesson 154 of 306

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.

MethodBehaviour
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

ClassWrites bytes to
FileOutputStream, Files.newOutputStream(path)A file
ByteArrayOutputStreamA growing byte[] in memory
socket.getOutputStream()A TCP connection
HttpServletResponse.getOutputStream() (servlets, Spring)The body of an HTTP response
System.out, System.errStandard output/error (they are PrintStreams)

Decorators, which wrap another OutputStream:

DecoratorAdds
BufferedOutputStreamA buffer that turns many small writes into few large ones
PrintStreamText output with print, println, printf (PrintStream lesson)
DataOutputStreamWriting Java primitive types (Data Streams lesson)
ObjectOutputStreamSerializing objects (Object Streams lesson)
GZIPOutputStream, ZipOutputStream, DeflaterOutputStreamCompression
CipherOutputStreamEncryption
DigestOutputStreamComputing 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 for Chennai ₹ (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 ByteArrayOutputStream has no effect, and its methods never actually fail, but they're declared with throws IOException where inherited from OutputStream, 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 a DigestOutputStream without 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:

  1. 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.
  2. 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 GZIPOutputStream is 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 with syncFlush = true). The result is a corrupt file that fails with EOFException.
  • If the destination must stay open (for example, a socket you'll keep using), call finish() instead of close(): it completes the compressed output without closing the underlying stream. ZipOutputStream and DeflaterOutputStream work 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:

  1. Building the chain in try-with-resources. Each resource wraps the previous one. They're closed in reverse order: the ZipOutputStream first — 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 (or finish()ed), the archive would have no central directory and most tools would report it as corrupt.
  2. Assigning in an expression. counter = new CountingOutputStream(digest) stores the counter in a variable while passing it to the ZipOutputStream constructor, so its count can be read after the try block, when all bytes have been written.
  3. Writing entries. For each report, putNextEntry starts a file inside the archive, write provides its content (compressed on the fly), and closeEntry completes it. The reports/ prefix creates a folder inside the ZIP. Passing StandardCharsets.UTF_8 makes entry names with non-ASCII characters portable.
  4. 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.
  5. Verification. ZipFile reads 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; with ZipOutputStream you can do the same by calling entry.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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java OutputStream and get answers drawn from it.

Signed-in readers only.