Skip to lesson

Buffering and why it matters

Writing a file one byte at a time can be a hundred times slower than writing it in blocks, even though the program does the same work. The difference is how often Java has to ask the operating system for help, and a buffer cuts that down.

One system call per byte versus per block

A buffer is a block of memory that holds data on its way to or from a slow device. A buffered stream moves data in large blocks, so the program makes far fewer slow trips to the disk.

A system call is a request from your program to the operating system, such as "write these bytes to the disk". Each one costs time, often about a microsecond or more, no matter how many bytes it carries.

Top: without a buffer, every read() of one byte is a separate trip to the disk. Bottom: with a buffer, one trip brings a block of 8192 bytes into memory and the many small reads are answered from that buffer.

Example 1 · Counting trips to the operating system

SystemCallCountDemo.javaJava
import java.io.BufferedOutputStream;import java.io.IOException;import java.io.OutputStream;
class CountingOutput extends OutputStream {     // stands in for a file: one call = one system call    int calls = 0;    long bytes = 0;
    @Override    public void write(int b) {        calls++;        bytes++;    }
    @Override    public void write(byte[] b, int off, int len) {        calls++;        bytes += len;    }}
public class SystemCallCountDemo {    public static void main(String[] args) throws IOException {        CountingOutput plain = new CountingOutput();        for (int i = 0; i < 20000; i++) {            plain.write('x');        }        System.out.println("Unbuffered: " + plain.bytes + " bytes in " + plain.calls + " calls");
        CountingOutput target = new CountingOutput();        try (OutputStream out = new BufferedOutputStream(target)) {            for (int i = 0; i < 20000; i++) {                out.write('x');            }        }        System.out.println("Buffered:   " + target.bytes + " bytes in " + target.calls + " calls");    }}
Output
Unbuffered: 20000 bytes in 20000 calls
Buffered:   20000 bytes in 3 calls

What this code does

  • CountingOutput counts how often it is called. For a real FileOutputStream, each of those calls would be a system call.
  • The BufferedOutputStream sent two full blocks of 8192 bytes and, on close, the last 3616 bytes: 3 calls instead of 20,000.

FileInputStream and FileOutputStream are unbuffered: every read() or write(int) is a separate system call for a single byte. Writing 300,000 bytes one by one makes 300,000 system calls. A buffer is an array in memory that collects bytes so they can be sent in one big block. With an 8192-byte buffer, the same 300,000 bytes need only about 37 system calls.

BufferedInputStream and BufferedOutputStream

BufferedOutputStream wraps another output stream and keeps written bytes in its own array, 8192 bytes by default. It passes them down only when the array is full, or when you call flush() or close().

Example 2 · BufferedInputStream reads big blocks underneath

BufferedReadDemo.javaJava
import java.io.BufferedInputStream;import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InputStream;
class CountingInput extends ByteArrayInputStream {   // stands in for a file    int calls = 0;
    CountingInput(byte[] data) {        super(data);    }
    @Override    public synchronized int read() {        calls++;        return super.read();    }
    @Override    public synchronized int read(byte[] b, int off, int len) {        calls++;        return super.read(b, off, len);    }}
public class BufferedReadDemo {    static int readAll(InputStream in) throws IOException {        int count = 0;        while (in.read() != -1) {            count++;        }        return count;    }
    public static void main(String[] args) throws IOException {        byte[] data = new byte[20000];
        CountingInput source1 = new CountingInput(data);        int n1 = readAll(source1);        System.out.println("Unbuffered: " + n1 + " bytes, " + source1.calls + " calls to the source");
        CountingInput source2 = new CountingInput(data);        int n2;        try (InputStream in = new BufferedInputStream(source2)) {            n2 = readAll(in);        }        System.out.println("Buffered:   " + n2 + " bytes, " + source2.calls + " calls to the source");    }}
Output
Unbuffered: 20000 bytes, 20001 calls to the source
Buffered:   20000 bytes, 4 calls to the source

What this code does

  • Both versions call read() one byte at a time. Without a buffer, every call goes to the source, plus one last call that returns -1.
  • With BufferedInputStream, the source is asked for blocks of 8192, 8192 and 3616 bytes, then once more to find the end: 4 calls in total.

Example 3 · A buffered copy, still one byte at a time

BufferedCopyDemo.javaJava
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 BufferedCopyDemo {    public static void main(String[] args) throws IOException {        Path dir = Files.createTempDirectory("buffered");        byte[] data = new byte[50000];        for (int i = 0; i < data.length; i++) {            data[i] = (byte) (i * 11);        }        Path song = Files.write(dir.resolve("ringtone.mp3"), data);        Path copy = dir.resolve("ringtone-copy.mp3");
        try (InputStream in = new BufferedInputStream(new FileInputStream(song.toFile()));             OutputStream out = new BufferedOutputStream(new FileOutputStream(copy.toFile()))) {            int b;            while ((b = in.read()) != -1) {                out.write(b);            }        }        System.out.println(copy.getFileName() + ": " + Files.size(copy) + " bytes");        System.out.println("Same as original: " + (Files.mismatch(song, copy) == -1));        Files.delete(song);        Files.delete(copy);        Files.delete(dir);    }}
Output
ringtone-copy.mp3: 50000 bytes
Same as original: true

What this code does

  • The loop is the simple byte-at-a-time loop, but both files are reached through a buffered layer, so the disk sees blocks of 8192 bytes.
  • Closing the output stream at the end of the try block flushes the last partial block, so the copy is complete.

BufferedInputStream does the reverse: it reads a whole block from the stream underneath and hands out bytes from memory until the block is used up. Your code still calls read() one byte at a time, but the file is read 8192 bytes at a time. A buffer helps when your code reads or writes small pieces. If you already copy with your own 8 KB byte[], the data moves in blocks anyway, and an extra buffered layer adds little.

new BufferedOutputStream(out, 65536) sets a different buffer size, but the default is fine for most programs.

Measuring time with System.nanoTime

System.nanoTime() returns a time value in nanoseconds that is only meaningful as a difference: read it before and after the work and subtract. Divide by 1,000,000 to get milliseconds.

Example 4 · Timing three ways to write a file

TimingDemo.javaJava
import java.io.BufferedOutputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.nio.file.Files;import java.nio.file.Path;
public class TimingDemo {    static final int SIZE = 300_000;
    static long unbuffered(Path file) throws IOException {        long start = System.nanoTime();        try (OutputStream out = new FileOutputStream(file.toFile())) {            for (int i = 0; i < SIZE; i++) {                out.write(i);            }        }        return (System.nanoTime() - start) / 1_000_000;    }
    static long buffered(Path file) throws IOException {        long start = System.nanoTime();        try (OutputStream out = new BufferedOutputStream(new FileOutputStream(file.toFile()))) {            for (int i = 0; i < SIZE; i++) {                out.write(i);            }        }        return (System.nanoTime() - start) / 1_000_000;    }
    static long blocks(Path file) throws IOException {        long start = System.nanoTime();        byte[] block = new byte[8192];        try (OutputStream out = new FileOutputStream(file.toFile())) {            int written = 0;            while (written < SIZE) {                int n = Math.min(block.length, SIZE - written);                for (int i = 0; i < n; i++) {                    block[i] = (byte) (written + i);                }                out.write(block, 0, n);                written += n;            }        }        return (System.nanoTime() - start) / 1_000_000;    }
    public static void main(String[] args) throws IOException {        Path dir = Files.createTempDirectory("timing");        Path file = dir.resolve("marks.bin");        System.out.println("Writing " + SIZE + " bytes");        System.out.println("Unbuffered, one byte per call: " + unbuffered(file) + " ms");        System.out.println("Buffered, one byte per call:   " + buffered(file) + " ms");        System.out.println("Unbuffered, 8 KB blocks:       " + blocks(file) + " ms");        System.out.println("File size: " + Files.size(file) + " bytes");        Files.delete(file);        Files.delete(dir);    }}
Sample output
Writing 300000 bytes
Unbuffered, one byte per call: 938 ms
Buffered, one byte per call:   11 ms
Unbuffered, 8 KB blocks:       3 ms
File size: 300000 bytes

What this code does

  • Your numbers will differ, but the pattern holds: 300,000 system calls are far slower than about 37 block writes. On this run the buffer made the same loop more than 80 times faster.
  • Writing your own 8 KB blocks is fastest because it skips even the per-byte method calls into the buffer. System.nanoTime() is read before and after each job, and only the difference is printed.

Use it instead of System.currentTimeMillis(), which follows the wall clock and can jump when the computer adjusts its time. Timings change from run to run and from computer to computer. The first run is often slower while the JVM compiles the code and the operating system warms its file cache, so run a test a few times and look at the size of the difference, not the exact numbers.

flush and what is lost without it

Bytes in a buffer are not in the file yet. flush() pushes them down to the stream underneath right away, and close() flushes and then releases the file.

Example 5 · flush, and the tail lost without close

FlushDemo.javaJava
import java.io.BufferedOutputStream;import java.io.FileOutputStream;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 FlushDemo {    public static void main(String[] args) throws IOException {        Path dir = Files.createTempDirectory("flush");        Path log = dir.resolve("upi-log.txt");        OutputStream out = new BufferedOutputStream(new FileOutputStream(log.toFile()));        out.write("TXN1 Rs 250\n".getBytes(StandardCharsets.UTF_8));        System.out.println("After write: " + Files.size(log) + " bytes on disk");        out.flush();        System.out.println("After flush: " + Files.size(log) + " bytes on disk");        out.close();
        Path report = dir.resolve("report.bin");        OutputStream forgot = new BufferedOutputStream(new FileOutputStream(report.toFile()));        for (int i = 0; i < 10000; i++) {            forgot.write(i);        }        System.out.println("No close yet: " + Files.size(report) + " of 10000 bytes on disk");        forgot.close();        System.out.println("After close:  " + Files.size(report) + " bytes on disk");
        Files.delete(log);        Files.delete(report);        Files.delete(dir);    }}
Output
After write: 0 bytes on disk
After flush: 12 bytes on disk
No close yet: 8192 of 10000 bytes on disk
After close:  10000 bytes on disk

What this code does

  • The 12 bytes of the log line sat in the buffer until flush() pushed them to the file.
  • Before close, only the first full 8192-byte block had reached the disk. If the program had ended at that point, the last 1808 bytes would have been lost for good.

If a program forgets close(), the bytes still in the buffer are simply lost: the JVM does not flush your streams when the program ends. The file then looks almost right but is missing its last part. Use try-with-resources so close always runs. Call flush() yourself only when someone needs the data before you close, for example a log line that must be on disk before a risky step.

Next step

Check your understanding

11 quick questions