00:00

BufferedInputStream Class in Java: Faster Byte Reading

Last updated:

Asking the operating system for data is slow compared with reading from memory. If a program reads a large file one byte at a time straight from disk, it makes one system request per byte. BufferedInputStream fixes this by fetching data in large blocks and serving small reads from memory.

This tutorial explains how buffering works, the class's constructors and methods, and two examples: measuring the difference buffering makes, and peeking at data with mark() and reset().

1. What Is BufferedInputStream in Java?

BufferedInputStream is a filter stream: it wraps another InputStream and adds two features, an internal buffer and support for mark() and reset(). It has been part of Java since version 1.0.

2. BufferedInputStream Class Hierarchy

BufferedInputStream class hierarchyBufferedInputStream extends FilterInputStream, which extends the abstract class InputStream, which extends Object. It implements Closeable and AutoCloseable, adds a buffer and mark and reset support, and can wrap any InputStream, such as a FileInputStream, a socket input stream or Files.newInputStream.ObjectextendsInputStreamabstract classextendsFilterInputStreamwraps another InputStreamextendsBufferedInputStreamadds a buffer and mark/resetCloseableAutoCloseableimplementsWraps any InputStreamFileInputStreamsocket.getInputStream()Files.newInputStream()

Swipe sideways to see the whole diagram.

3. How Buffering Works

  1. On the first read(), the stream fills its internal buffer with a large block from the wrapped stream.
  2. Later reads are answered from the buffer in memory, without touching the file.
  3. When the buffer is used up, it is refilled with the next block.

The result is the same data with far fewer expensive calls to the underlying source.

4. Constructors of BufferedInputStream

ConstructorDescription
BufferedInputStream(InputStream in)Wraps in with a buffer of a default size chosen by the JDK.
BufferedInputStream(InputStream in, int size)Wraps in with a buffer of size bytes; throws IllegalArgumentException if size is 0 or less.

5. Commonly Used Methods

MethodDescription
int read()Returns the next byte from the buffer, refilling it when needed.
int read(byte[] b, int off, int len)Reads up to len bytes.
void mark(int readlimit)Remembers the current position; stays valid while at most readlimit bytes are read.
void reset()Returns to the marked position.
boolean markSupported()Always true for this class.
long skip(long n)Skips up to n bytes.
int available()Bytes in the buffer plus an estimate from the wrapped stream.
void close()Closes this stream and the wrapped stream.

6. Example: Counting Calls to the File

A product catalog file of 10,000 bytes is read one byte at a time, first directly and then through a 4 KB buffer. A small FilterInputStream subclass counts every request that reaches the file stream.

CallCounter.java
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;

public class CallCounter {

    // Counts how often the file itself is asked for data
    static class CountingStream extends FilterInputStream {
        int calls;
        CountingStream(InputStream in) { super(in); }
        @Override public int read() throws IOException { calls++; return super.read(); }
        @Override public int read(byte[] b, int off, int len) throws IOException { calls++; return in.read(b, off, len); }
    }

    static int readAllBytesOneByOne(InputStream in) throws IOException {
        int total = 0;
        while (in.read() != -1) {
            total++;
        }
        return total;
    }

    public static void main(String[] args) throws IOException {
        Path file = Files.createTempFile("catalog", ".bin");
        Files.write(file, new byte[10_000]);

        try (CountingStream raw = new CountingStream(new FileInputStream(file.toFile()))) {
            int bytes = readAllBytesOneByOne(raw);
            System.out.println("Unbuffered: " + bytes + " bytes, " + raw.calls + " calls to the file");
        }
        CountingStream counter = new CountingStream(new FileInputStream(file.toFile()));
        try (InputStream buffered = new BufferedInputStream(counter, 4096)) {
            int bytes = readAllBytesOneByOne(buffered);
            System.out.println("Buffered:   " + bytes + " bytes, " + counter.calls + " calls to the file");
        }
        Files.delete(file);
    }
}
Output
Unbuffered: 10000 bytes, 10001 calls to the file
Buffered:   10000 bytes, 4 calls to the file

How the code works

  1. CountingStream wraps the file stream and increases calls each time data is requested from it.
  2. Without a buffer, each of the 10,000 read() calls, plus the final one that returns -1, reaches the file: 10,001 calls.
  3. With a 4,096-byte buffer, the file is asked for data only four times: two full blocks, one block of 1,808 bytes and one call that reports the end.
  4. The program reads the same 10,000 bytes in both cases.

7. Example: Peeking with mark() and reset()

An API gateway receives messages in different formats. It must look at the first bytes to choose a parser, but the parser still needs the complete message. mark() and reset() make that possible.

PeekAndRewind.java
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class PeekAndRewind {

    static void handle(InputStream source) throws IOException {
        try (InputStream in = new BufferedInputStream(source)) {
            in.mark(2);                                  // remember this position
            byte[] magic = in.readNBytes(2);
            in.reset();                                  // go back to the mark
            String type = (magic[0] == '{') ? "JSON" : (magic[0] == '<') ? "XML" : "plain text";
            String all = new String(in.readAllBytes(), StandardCharsets.UTF_8);
            System.out.println(type + " -> " + all);
        }
    }

    public static void main(String[] args) throws IOException {
        handle(new ByteArrayInputStream("{\"order\":17}".getBytes(StandardCharsets.UTF_8)));
        handle(new ByteArrayInputStream("<order id=\"18\"/>".getBytes(StandardCharsets.UTF_8)));
        handle(new ByteArrayInputStream("order 19".getBytes(StandardCharsets.UTF_8)));
    }
}
Output
JSON -> {"order":17}
XML -> <order id="18"/>
plain text -> order 19

How the code works

  1. mark(2) remembers the start of the stream for the next two bytes.
  2. readNBytes(2) peeks at the first characters to detect JSON ({) or XML (<).
  3. reset() rewinds to the mark, so readAllBytes() returns the whole message.

8. Common Mistakes and Best Practices

  • Double buffering. Wrapping a stream that is already buffered adds little; one buffer is enough.
  • Reading past the mark limit. After more than readlimit bytes, reset() may fail with an IOException.
  • Using the wrapped stream directly. Once wrapped, read only through the buffered stream, or bytes will be skipped.
  • Buffering large array reads. When you already read big blocks with read(byte[]), buffering gains little.

9. Java Version Improvements and Java 25 Updates

Java versionChange
Java 1.0BufferedInputStream with buffering and mark()/reset().
Java 9 to 12Inherits readAllBytes(), readNBytes(), transferTo() and skipNBytes().
Java 25No API changes. The default buffer size is an implementation detail; pass a size if you need a specific one.

10. Summary

  • BufferedInputStream wraps any InputStream and reads it in large blocks.
  • It turns many small reads into a few large ones, which is much faster for files and sockets.
  • It supports mark() and reset() for peeking at data.
  • Read only through the buffered stream and close it to close the wrapped stream too.

Related Tutorials

11. Official Java Documentation References