Java buffered streams

Every read or write on an unbuffered file stream becomes a call into the operating system. A buffered stream turns millions of small calls into a few hundred large ones, which makes byte-at-a-time I/O more than ten times faster. This page counts those calls, measures the difference, and shows the read-ahead, flush and close traps that buffering brings with it.

Contents

How a buffered stream works

Each call to FileInputStream.read() or FileOutputStream.write(int) becomes a system call, a switch from your program into the operating system kernel. That switch costs far more than moving one byte, so code that reads or writes small pieces spends most of its time on the switches.

A buffered stream sits between your code and the real stream and keeps an array, 8,192 bytes or characters by default. A BufferedInputStream fills the array with one large read, then serves your small reads from memory until the array is empty. A BufferedOutputStream collects your small writes in the array and passes it on in one call when it is full, when you call flush(), or when you close the stream. Both follow the decorator pattern: they wrap any other stream and have the same interface, so code that writes to an OutputStream works unchanged with or without the buffer.

The buffered classes
ClassSinceWrapsUnitExtra methods
BufferedInputStreamJava 1.0InputStreamBytesmark, reset
BufferedOutputStreamJava 1.0OutputStreamBytesflush
BufferedReaderJava 1.1ReaderCharactersreadLine, lines (Java 8), mark, reset
BufferedWriterJava 1.1WriterCharactersnewLine, flush
Files.newBufferedReader / newBufferedWriterJava 7A fileCharactersCreates the above with UTF-8 by default

Buffering pays off when your code makes many small calls. It does nothing for code that already reads or writes large arrays, and it brings two duties: data you write is not in the file until the buffer is flushed, and data the buffer has read ahead is no longer in the underlying stream. Both are shown running below. All programs were compiled and run on JDK 21.

Counting the calls that reach the real stream

To see exactly what a buffer does, the program replaces the file with small streams that count how often they are called. Counting is exact and the same on every machine, unlike timings. Two million single bytes were chosen because that is a realistic count for a few megabytes written by code that handles one value at a time.

Java
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class SysCallCount {

    // Stands in for a FileOutputStream: counts how often it is called
    static class CountingOut extends OutputStream {
        long calls;
        long bytes;

        @Override
        public void write(int b) {
            calls++;
            bytes++;
        }

        @Override
        public void write(byte[] b, int off, int len) {
            calls++;
            bytes += len;
        }
    }

    // Stands in for a FileInputStream holding 2,000,000 bytes
    static class CountingIn extends InputStream {
        long calls;
        int left = 2000000;

        @Override
        public int read() {
            calls++;
            return left-- > 0 ? 7 : -1;
        }

        @Override
        public int read(byte[] b, int off, int len) {
            calls++;
            if (left <= 0) {
                return -1;
            }
            int n = Math.min(len, left);
            left -= n;
            return n;
        }
    }

    public static void main(String[] args) throws IOException {
        CountingOut raw = new CountingOut();
        for (int i = 0; i < 2000000; i++) {
            raw.write(i);
        }
        System.out.printf("%-44s %,9d calls%n", "2,000,000 write(int), no buffer:", raw.calls);

        CountingOut target = new CountingOut();
        try (OutputStream out = new BufferedOutputStream(target)) {
            for (int i = 0; i < 2000000; i++) {
                out.write(i);
            }
        }
        System.out.printf("%-44s %,9d calls%n", "the same through BufferedOutputStream:",
                target.calls);

        target = new CountingOut();
        try (OutputStream out = new BufferedOutputStream(target, 64 * 1024)) {
            for (int i = 0; i < 2000000; i++) {
                out.write(i);
            }
        }
        System.out.printf("%-44s %,9d calls%n", "with a 64 KB buffer:", target.calls);

        target = new CountingOut();
        try (OutputStream out = new BufferedOutputStream(target)) {
            out.write(new byte[100]);                       // fits: stays in the buffer
            out.write(new byte[100000]);                   // larger than the buffer
            System.out.printf("%-44s %,9d calls, %,d bytes%n",
                    "write 100 bytes, then 100,000 bytes:", target.calls, target.bytes);
        }

        CountingIn source = new CountingIn();
        try (InputStream in = new BufferedInputStream(source)) {
            while (in.read() != -1) {
                // one byte at a time from the buffer
            }
        }
        System.out.printf("%-44s %,9d calls%n", "2,000,000 read() through BufferedInputStream:",
                source.calls);

        source = new CountingIn();
        try (InputStream in = new BufferedInputStream(source)) {
            byte[] chunk = new byte[65536];
            while (in.read(chunk) != -1) {
                // large reads go straight to the source
            }
        }
        System.out.printf("%-44s %,9d calls%n", "read(byte[65536]) through BufferedInputStream:",
                source.calls);
    }
}

Output:

Output
2,000,000 write(int), no buffer:             2,000,000 calls
the same through BufferedOutputStream:             245 calls
with a 64 KB buffer:                                31 calls
write 100 bytes, then 100,000 bytes:                 2 calls, 100,100 bytes
2,000,000 read() through BufferedInputStream:       246 calls
read(byte[65536]) through BufferedInputStream:        32 calls
  • Without a buffer, 2,000,000 calls to write(int) made 2,000,000 calls to the underlying stream. On a FileOutputStream, each of those is a system call.
  • BufferedOutputStream reduced that to 245 calls: 2,000,000 divided by the 8,192-byte buffer, rounded up. A 64 KB buffer passed to the constructor reduced it to 31.
  • Writing 100 bytes and then 100,000 bytes made only 2 calls. The 100 bytes waited in the buffer; the 100,000-byte array was larger than the buffer, so the stream flushed the 100 bytes and then wrote the large array straight through instead of copying it in pieces. The Javadoc of BufferedOutputStream.write(byte[], int, int) documents this.
  • Reading is symmetric. 2,000,000 single-byte reads through BufferedInputStream made 246 calls to the source, the last one returning end of stream. With 64 KB reads the buffer was bypassed, and the source saw 32 calls of up to 65,536 bytes each.

What the saved calls are worth

Now the same loops run against a real file: 2 million single bytes written and read with and without a buffer, best of 3 runs each. Every read is checked against the expected sum of all bytes, 254,991,808, so a fast version cannot be skipping work. The last line reads the file in 8 KB chunks with no buffered stream at all.

Java
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;

public class WhyBuffer {

    static final int SIZE = 2000000;

    interface Job {
        void run() throws IOException;
    }

    static long best(Job job) throws IOException {
        long best = Long.MAX_VALUE;
        for (int i = 0; i < 3; i++) {
            long start = System.nanoTime();
            job.run();
            best = Math.min(best, System.nanoTime() - start);
        }
        return best;
    }

    static void writeBytes(OutputStream out) throws IOException {
        try (out) {
            for (int i = 0; i < SIZE; i++) {
                out.write(i & 0xFF);                        // one byte per call
            }
        }
    }

    static void readBytes(InputStream in) throws IOException {
        long sum = 0;
        try (in) {
            int b;
            while ((b = in.read()) != -1) {                // one byte per call
                sum += b;
            }
        }
        if (sum != 254991808L) {
            throw new IllegalStateException("wrong checksum " + sum);
        }
    }

    static void readChunks(InputStream in) throws IOException {
        byte[] chunk = new byte[8192];
        long total = 0;
        try (in) {
            int n;
            while ((n = in.read(chunk)) != -1) {
                total += n;
            }
        }
        if (total != SIZE) {
            throw new IllegalStateException("wrong size " + total);
        }
    }

    public static void main(String[] args) throws IOException {
        Path f = Files.createTempFile("bytes", ".bin");
        String file = f.toString();

        long rawWrite = best(() -> writeBytes(new FileOutputStream(file)));
        long bufWrite = best(() -> writeBytes(
                new BufferedOutputStream(new FileOutputStream(file))));
        long rawRead = best(() -> readBytes(new FileInputStream(file)));
        long bufRead = best(() -> readBytes(new BufferedInputStream(new FileInputStream(file))));
        long chunkRead = best(() -> readChunks(new FileInputStream(file)));

        System.out.println("2,000,000 bytes, best of 3 runs");
        System.out.printf("write one byte per call: unbuffered %6.1f ms, buffered %5.1f ms%n",
                rawWrite / 1e6, bufWrite / 1e6);
        System.out.printf("read  one byte per call: unbuffered %6.1f ms, buffered %5.1f ms%n",
                rawRead / 1e6, bufRead / 1e6);
        System.out.printf("read 8 KB chunks, no buffered stream:            %5.1f ms%n",
                chunkRead / 1e6);
        Files.delete(f);
    }
}

Output (rough comparison on a 2-CPU Linux VM, JDK 21; absolute times will differ on yours):

Output
2,000,000 bytes, best of 3 runs
write one byte per call: unbuffered  574.3 ms, buffered  41.2 ms
read  one byte per call: unbuffered  455.3 ms, buffered  28.5 ms
read 8 KB chunks, no buffered stream:              0.6 ms
  • The buffer made the same single-byte loop more than ten times faster in both directions. The loop did not change; only the number of system calls did.
  • Reading in 8 KB chunks, with no buffered stream, was faster again by a large factor, because there was no per-byte method call either. When your own code already works in large arrays, a buffered stream adds a copy and nothing else.
  • Output is where a missing buffer hurts most often in practice: a FileOutputStream or DataOutputStream that writes small values one at a time.

Buffer size beyond the default rarely matters; the measurement on the large files page shows the gain flattening out between 8 KB and 64 KB.

Traps: read-ahead, flushing and close order

Buffering changes when data moves, and three common bugs come from forgetting that. The program shows each of them with a message that has a text header and a binary body, and with a real file.

Java
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class BufferTraps {

    public static void main(String[] args) throws IOException {
        // Trap 1: the buffer reads ahead, so the raw stream has nothing left
        byte[] message = ("HEADER v1\n" + "x".repeat(5000)).getBytes(StandardCharsets.US_ASCII);
        InputStream raw = new ByteArrayInputStream(message);
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(raw, StandardCharsets.US_ASCII));
        String header = reader.readLine();
        byte[] rest = raw.readAllBytes();               // read the body from the raw stream
        System.out.println("header: " + header + ", message bytes: " + message.length);
        System.out.println("body bytes left in the raw stream: " + rest.length);
        System.out.println("body chars still in the reader:   " + reader.lines()
                .mapToInt(String::length).sum());

        // Trap 2: data sits in the buffer until flush or close
        Path file = Files.createTempFile("buffered", ".bin");
        FileOutputStream fileOut = new FileOutputStream(file.toFile());
        OutputStream out = new BufferedOutputStream(fileOut);
        out.write(new byte[100]);
        System.out.println("after write(100 bytes): file has " + Files.size(file) + " bytes");
        out.flush();
        System.out.println("after flush():          file has " + Files.size(file) + " bytes");

        // Trap 3: closing the inner stream first makes the outer close fail
        out.write(new byte[50]);
        fileOut.close();
        try {
            out.close();
        } catch (IOException e) {
            System.out.println("outer close after inner close: IOException: " + e.getMessage());
        }
        System.out.println("final file size: " + Files.size(file) + " bytes (50 bytes lost)");
        Files.delete(file);
    }
}

Output:

Output
header: HEADER v1, message bytes: 5010
body bytes left in the raw stream: 0
body chars still in the reader:   5000
after write(100 bytes): file has 0 bytes
after flush():          file has 100 bytes
outer close after inner close: IOException: Stream Closed
final file size: 100 bytes (50 bytes lost)
  • Read-ahead: readLine returned only the 9-character header, but the reader had already taken all 5,010 bytes from the raw stream to fill its buffer. Reading the body from the raw stream gave 0 bytes; the 5,000 characters were inside the reader. Once a stream is wrapped, read only through the wrapper. Note that InputStreamReader reads bytes ahead in blocks too, so the problem appears even without a BufferedReader. Protocols that mix text lines and binary data have to parse the header from the bytes themselves.
  • Flushing: after writing 100 bytes the file still had 0 bytes, because they were in the buffer. flush() moved them to the file. A program that exits without closing its streams loses whatever is still buffered; the JVM does not flush them at exit.
  • Close order: the program closed the FileOutputStream first. Closing the buffered stream then tried to flush the last 50 bytes into a closed stream and failed with IOException: Stream Closed, so the file kept 100 bytes and the 50 were lost. Close only the outermost stream; it flushes and then closes everything it wraps. Try-with-resources on the outer stream does exactly that.

mark and reset: looking ahead without consuming

A buffer can also give data back. mark(limit) remembers the current position, and reset() returns to it, as long as no more than limit bytes were read in between. A plain FileInputStream cannot do this. The program uses it to detect whether input is GZIP-compressed by its first two bytes, the magic number 0x1f 0x8b, and then reads it correctly either way. The two inputs carry the same text, once plain and once compressed.

Java
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
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 PeekMagic {

    // Returns a stream of the content, unzipping it first if it starts with the GZIP magic
    static InputStream open(InputStream source) throws IOException {
        BufferedInputStream in = new BufferedInputStream(source);
        in.mark(2);
        int b1 = in.read();
        int b2 = in.read();
        in.reset();                                     // back to byte 0
        boolean gzip = b1 == 0x1f && b2 == 0x8b;
        System.out.printf("  first bytes %02x %02x -> %s%n", b1, b2, gzip ? "gzip" : "plain");
        return gzip ? new GZIPInputStream(in) : in;
    }

    public static void main(String[] args) throws IOException {
        byte[] text = "same content either way".getBytes(StandardCharsets.UTF_8);
        ByteArrayOutputStream zipped = new ByteArrayOutputStream();
        try (GZIPOutputStream gz = new GZIPOutputStream(zipped)) {
            gz.write(text);
        }

        for (byte[] input : new byte[][] {text, zipped.toByteArray()}) {
            System.out.println("input of " + input.length + " bytes:");
            try (InputStream in = open(new ByteArrayInputStream(input))) {
                System.out.println("  read: " + new String(in.readAllBytes(),
                        StandardCharsets.UTF_8));
            }
        }

        Path file = Files.createTempFile("plain", ".txt");
        Files.write(file, text);
        try (InputStream fileIn = new FileInputStream(file.toFile());
             InputStream buffered = new BufferedInputStream(new FileInputStream(file.toFile()))) {
            System.out.println("FileInputStream.markSupported():     " + fileIn.markSupported());
            System.out.println("BufferedInputStream.markSupported(): "
                    + buffered.markSupported());
        }
        Files.delete(file);
    }
}

Output:

Output
input of 23 bytes:
  first bytes 73 61 -> plain
  read: same content either way
input of 43 bytes:
  first bytes 1f 8b -> gzip
  read: same content either way
FileInputStream.markSupported():     false
BufferedInputStream.markSupported(): true
  • The plain input starts with 0x73 0x61, the letters "sa". The compressed input, 43 bytes for 23 bytes of text, starts with 0x1f 0x8b. GZIP adds an 18-byte header and trailer, so tiny inputs grow; see ZIP and GZIP.
  • After reset(), the two peeked bytes were read again by GZIPInputStream, which needs them to check the header. Without mark and reset, the code would have to pass the two bytes along separately.
  • markSupported() is false for FileInputStream and true for BufferedInputStream. Code that receives an unknown InputStream and needs to peek should wrap it, as open does.

BufferedReader and the convenience methods

BufferedReader adds line reading on top of buffering. The program reads from in-memory strings, so the exact input is visible: a string that mixes Windows (\r\n), old Mac (\r) and Unix (\n) line endings, a CSV that may or may not start with a header, and a reset that comes too late. It ends with the methods that later Java versions added for whole-stream work.

Java
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;

public class ReaderFeatures {

    public static void main(String[] args) throws IOException {
        // readLine accepts all three line-ending styles and removes them
        String mixed = "windows\r\nold-mac\runix\nlast";
        try (BufferedReader r = new BufferedReader(new StringReader(mixed))) {
            String line;
            int n = 0;
            while ((line = r.readLine()) != null) {
                System.out.println("line " + (++n) + ": [" + line + "]");
            }
        }

        // mark/reset: peek at the start, then read from the beginning again
        String csv = "id,name\n1,Ana\n2,Ben\n";
        try (BufferedReader r = new BufferedReader(new StringReader(csv))) {
            r.mark(1024);                            // may read up to 1024 chars before reset
            String header = r.readLine();
            boolean hasHeader = header.startsWith("id");
            r.reset();
            if (hasHeader) {
                r.readLine();                        // skip it for real this time
            }
            System.out.println("header detected: " + hasHeader + ", data rows: "
                    + r.lines().count());
        }

        // reset after reading past the mark limit
        try (BufferedReader r = new BufferedReader(new StringReader("x".repeat(20000)), 16)) {
            r.mark(10);
            r.skip(100);
            r.reset();
        } catch (IOException e) {
            System.out.println("reset beyond the read-ahead limit: " + e.getMessage());
        }

        // Convenience methods on InputStream and Reader
        byte[] data = "0123456789abcdef".getBytes(StandardCharsets.US_ASCII);
        InputStream in = new ByteArrayInputStream(data);
        in.skipNBytes(4);                                       // Java 12
        byte[] six = in.readNBytes(6);                          // Java 11
        byte[] rest = in.readAllBytes();                        // Java 9
        System.out.println("skipNBytes(4), readNBytes(6): " + new String(six,
                StandardCharsets.US_ASCII) + ", readAllBytes: " + new String(rest,
                StandardCharsets.US_ASCII));

        StringWriter copy = new StringWriter();
        long chars = new StringReader("copied by Reader.transferTo").transferTo(copy); // Java 10
        System.out.println(chars + " chars: " + copy);
    }
}

Output:

Output
line 1: [windows]
line 2: [old-mac]
line 3: [unix]
line 4: [last]
header detected: true, data rows: 2
reset beyond the read-ahead limit: Mark invalid
skipNBytes(4), readNBytes(6): 456789, readAllBytes: abcdef
27 chars: copied by Reader.transferTo
  • readLine recognized all three endings and returned four clean lines with no stray \r. The last line has no ending and is still returned.
  • mark(1024) allowed the reader to read the first line, decide it was a header, rewind and then skip it, leaving 2 data rows.
  • With a 16-character buffer and mark(10), skipping 100 characters went past the limit, and reset() threw IOException: Mark invalid. A limit larger than the buffer is allowed; the reader then grows its buffer to the limit, so a huge limit costs memory.
  • skipNBytes (Java 12) skips exactly 4 bytes or throws, unlike skip, which may skip fewer. readNBytes(6) (Java 11) returned "456789" and readAllBytes (Java 9) the rest. Reader.transferTo (Java 10) and InputStream.transferTo (Java 9) copy a whole stream with an internal buffer, so a hand-written copy loop is no longer needed.

For reading whole text files line by line, see reading a text file; for writing, see writing a text file.

When to add a buffer

Choosing whether and how to buffer
SituationUse
Small reads or writes on a file or socket streamWrap it in BufferedInputStream or BufferedOutputStream
Text from a fileFiles.newBufferedReader; it is already buffered
Text to a fileFiles.newBufferedWriter, closed with try-with-resources
Your code already reads or writes 8 KB or more per callNo buffered stream needed
Copying a whole streamin.transferTo(out)
Peeking at the first bytes before deciding how to readBufferedInputStream with mark and reset
Text header followed by binary dataParse the header from bytes; do not mix a reader with the raw stream
A reader from Files.newBufferedReaderDo not wrap it in another BufferedReader; that only adds a copy