Java I/O Filters: Buffered, Data and Pushback Streams
Combine Java I/O stream filters: why FileInputStream and DataInputStream have separate jobs, layering DataInputStream over BufferedInputStream over FileInputStream, what buffering saves, PushbackInputStream, append mode, compression filters and writing your own filter.
kvi5hnuCode Sprout team member8 min readOn this page
A FileInputStream can read bytes from a file, and that's all it can do. You can read a byte from it, but not an int, a double or a string. A DataInputStream, which you'll meet properly in article 22, can read numbers, but it has no idea how to get bytes out of a file. Java splits these responsibilities on purpose and leaves it to you to combine the pieces. This article shows how that layering works and why it's more flexible than it first looks.
Sources and filters
There are two kinds of input streams:
- Sources get bytes from somewhere:
FileInputStreamfrom a file,ByteArrayInputStreamfrom an array, the stream returned bySocket.getInputStream()from the network. - Filters take another input stream in their constructor and add a capability on top of it:
DataInputStreamassembles bytes into numbers,BufferedInputStreamadds buffering,PushbackInputStreamadds lookahead, andGZIPInputStreamandZipInputStreamdecompress.
To read numbers from a file, you create the source and pass it to the filter:
var fin = new FileInputStream("employee.dat");
var din = new DataInputStream(fin);
double x = din.readDouble();
The filter classes extend FilterInputStream and FilterOutputStream. These keep a reference to the wrapped stream, in a protected field called in or out, and pass all calls through to it by default. Subclasses override the methods whose behavior they change. This is the decorator design pattern: each layer has the same type as the thing it wraps, so layers stack in any combination.
Stacking filters
Plain file streams aren't buffered. Every read() call asks the operating system for one more byte, which is very slow. It's much faster to fetch a block of bytes and hand them out from memory. If you want buffering and the data methods for a file, stack three layers:
var din = new DataInputStream(
new BufferedInputStream(
new FileInputStream("employee.dat")));
Read the constructors from the inside out: the file supplies bytes, the buffer fetches them in blocks, and the data stream turns them into values. The DataInputStream goes outermost because that's the class whose methods you want to call, and you want those calls to go through the buffer. Output works the same way:
var dout = new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream("employee.dat")));

How much does buffering save? In the demo, reading 100,000 bytes one at a time makes 100,001 calls to the underlying stream without a buffer, but only 14 with one, since the default buffer holds 8,192 bytes. For a real file, each of those calls is a trip into the operating system.
Closing a chain
Close only the outermost stream. Closing a filter closes the stream it wraps, and closing a buffered output stream first flushes its buffer. With try-with-resources, declare the whole chain as one resource:
try (var out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)))) {
out.writeInt(1234);
}
There's a small catch: if a filter's constructor throws, the inner stream that was already opened isn't closed. Most filter constructors can't fail, but GZIPInputStream reads a header and can throw. If that matters, declare each layer as its own resource: try (var fin = new FileInputStream(f); var gin = new GZIPInputStream(fin)) { ... }.
Append mode
new FileOutputStream(name) truncates an existing file. Its previous contents are gone. Pass true as a second argument to append to the end instead: new FileOutputStream(name, true).
Looking ahead with PushbackInputStream
When parsing input, you often need to peek at the next byte to decide what to do. PushbackInputStream lets you read a byte and unread it:
var pbin = new PushbackInputStream(new BufferedInputStream(new FileInputStream("data.xml")));
int b = pbin.read();
if (b != '<') pbin.unread(b);
unread doesn't touch the source. It stores the byte in a small pushback buffer, and the next read returns it first. The buffer holds one byte by default. Pass a larger size to the constructor to push back several bytes. Bytes come back in reverse order of unreading, like a stack, so unread the last byte read first.
A pushback stream can only read and unread. If you also want readInt and friends, stack a DataInputStream on top and keep references to both layers:
var pbin = new PushbackInputStream(new BufferedInputStream(new FileInputStream("data.bin")));
var din = new DataInputStream(pbin);
Peek through pbin, read values through din. Both see the same bytes.
Why this design?
Other languages' I/O libraries simply buffer by default and offer lookahead built in, so Java's chains of constructors can feel clumsy. The payoff is flexibility. Any filter combines with any source. To read numbers from a compressed file, wrap a DataInputStream around a GZIPInputStream around a FileInputStream. To read them from a ZIP entry, use a ZipInputStream as the middle layer (article 24). You can also write your own filters, such as one that counts bytes, computes a checksum or transforms data, and they'll work in any chain. The demo has two examples.
In everyday code you rarely build long chains by hand. Files.newInputStream, Files.newBufferedReader and the other Files methods (article 26) open a file with suitable defaults. For text, you'll use readers and writers, starting with the next article.
A complete example
import java.io.*;
import java.nio.file.*;
import java.util.zip.*;
public class Solution {
// a filter that counts how often the stream below it is asked for data
static class CallCountingInputStream extends FilterInputStream {
int calls;
CallCountingInputStream(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 super.read(b, off, len);
}
}
// a filter that changes the data: lowercase ASCII letters become uppercase
static class UpperCaseOutputStream extends FilterOutputStream {
UpperCaseOutputStream(OutputStream out) { super(out); }
@Override
public void write(int b) throws IOException {
out.write(b >= 'a' && b <= 'z' ? b - 32 : b);
}
}
public static void main(String[] args) throws IOException {
Path file = Files.createTempFile("filters", ".dat");
// data methods + buffering + a file, layered from the outside in
try (var out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file.toFile())))) {
out.writeInt(1234);
out.writeDouble(Math.PI);
out.writeUTF("José");
}
System.out.println("file size: " + Files.size(file) + " bytes");
try (var in = new DataInputStream(new BufferedInputStream(new FileInputStream(file.toFile())))) {
System.out.println("read back: " + in.readInt() + ", " + in.readDouble() + ", " + in.readUTF());
}
// append mode adds to the end instead of replacing the file
try (var out = new DataOutputStream(new FileOutputStream(file.toFile(), true))) {
out.writeInt(42);
}
System.out.println("after appending an int: " + Files.size(file) + " bytes");
Files.delete(file);
// buffering reduces the number of calls to the underlying stream
byte[] data = new byte[100_000];
var unbuffered = new CallCountingInputStream(new ByteArrayInputStream(data));
while (unbuffered.read() != -1) { }
var counter = new CallCountingInputStream(new ByteArrayInputStream(data));
try (var buffered = new BufferedInputStream(counter)) {
while (buffered.read() != -1) { }
}
System.out.println("calls without a buffer: " + unbuffered.calls + ", with a buffer: " + counter.calls);
// peeking with a pushback stream
try (var pin = new PushbackInputStream(new ByteArrayInputStream("<tag>text".getBytes()), 2)) {
int b = pin.read();
if (b != '<') pin.unread(b);
System.out.println("starts with '<': " + (b == '<'));
int c1 = pin.read(), c2 = pin.read();
pin.unread(c2);
pin.unread(c1);
System.out.println("after unreading two bytes: " + new String(pin.readAllBytes()));
}
// pushback plus data methods: keep a reference to both
var bytes = new ByteArrayOutputStream();
try (var dout = new DataOutputStream(bytes)) {
dout.writeByte(1);
dout.writeInt(777);
}
var pin = new PushbackInputStream(new ByteArrayInputStream(bytes.toByteArray()));
var din = new DataInputStream(pin);
int tag = pin.read();
if (tag == 1) System.out.println("tag 1 found, value: " + din.readInt());
// a custom filter in the middle of a chain
var sink = new ByteArrayOutputStream();
try (var out = new PrintStream(new UpperCaseOutputStream(sink), true)) {
out.print("filters can transform data");
}
System.out.println(sink);
// compression is just another filter
var compressed = new ByteArrayOutputStream();
try (var out = new DataOutputStream(new GZIPOutputStream(compressed))) {
for (int i = 0; i < 1000; i++) out.writeInt(i % 10);
}
System.out.println("4000 bytes of ints compressed to fewer than 400: " + (compressed.size() < 400));
try (var in = new DataInputStream(new GZIPInputStream(new ByteArrayInputStream(compressed.toByteArray())))) {
long sum = 0;
for (int i = 0; i < 1000; i++) sum += in.readInt();
System.out.println("sum after decompressing: " + sum);
}
}
}
file size: 19 bytes
read back: 1234, 3.141592653589793, José
after appending an int: 23 bytes
calls without a buffer: 100001, with a buffer: 14
starts with '<': true
after unreading two bytes: tag>text
tag 1 found, value: 777
FILTERS CAN TRANSFORM DATA
4000 bytes of ints compressed to fewer than 400: true
sum after decompressing: 4500
The file holds 19 bytes: 4 for the int, 8 for the double and 7 for "José" in writeUTF's format (a two-byte length, then 5 bytes, because é takes two).
Common questions
Are the streams from Files.newInputStream and Files.newOutputStream buffered?
No. They are thin wrappers around a file channel, so many small reads or writes go to the operating system one by one. Wrap them in a BufferedInputStream or BufferedOutputStream when you read or write in small pieces. Bulk methods such as readAllBytes and transferTo do not need a buffer.
Do I need to call flush() before close()?
No, close() on a buffered stream flushes first. Call flush() when the stream stays open but the receiver must see the data now, for example on a socket or a log file that someone is watching.
Does the order of the layers matter?
Yes. The class whose methods you call goes outermost, and buffering goes as close to the source as possible. new BufferedInputStream(new DataInputStream(file)) would compile, but the readInt calls you want are not available on the outer type, and the data layer would read unbuffered.
When should I write my own filter stream?
When a cross-cutting step should work with any stream: counting bytes, computing a checksum on the fly (the JDK already has CheckedInputStream and DigestInputStream), limiting the size of an upload, or logging traffic. Extend FilterInputStream and override both read() and read(byte[], int, int), since the bulk method is the one most callers use.
Is PushbackInputStream the same as mark and reset?
Both let you look ahead, but pushback lets you put back any bytes, even ones you never read, while reset returns to an earlier position in the actual data. Pushback works with every source; mark and reset only with streams that support it.
API reference
java.io.FileInputStream and java.io.FileOutputStream
| Constructor | Description |
|---|---|
FileInputStream(String name), FileInputStream(File file) | opens a file for reading |
FileOutputStream(String name), FileOutputStream(File file) | opens a file for writing, replacing existing contents |
FileOutputStream(String name, boolean append), FileOutputStream(File file, boolean append) | if append is true, writes at the end of an existing file |
java.io.BufferedInputStream and java.io.BufferedOutputStream
| Constructor | Description |
|---|---|
BufferedInputStream(InputStream in), BufferedInputStream(InputStream in, int size) | reads from in in blocks, using an internal buffer |
BufferedOutputStream(OutputStream out), BufferedOutputStream(OutputStream out, int size) | collects bytes and writes them to out when the buffer is full or flushed |
java.io.PushbackInputStream
| Method | Description |
|---|---|
PushbackInputStream(InputStream in), PushbackInputStream(InputStream in, int size) | a stream with a one-byte or size-byte pushback buffer |
void unread(int b), void unread(byte[] b) | pushes bytes back so the next read returns them |
java.io.FilterInputStream and java.io.FilterOutputStream
| Member | Description |
|---|---|
protected InputStream in, protected OutputStream out | the wrapped stream |
FilterInputStream(InputStream in), FilterOutputStream(OutputStream out) | constructors for subclasses; all methods delegate to the wrapped stream |
Summary
- Source streams get bytes from somewhere. Filter streams wrap another stream and add a capability.
- Stack filters by passing one stream to another's constructor. The outermost layer provides the methods you call:
new DataInputStream(new BufferedInputStream(new FileInputStream(f))). - Buffering cuts the number of calls to the operating system dramatically. Closing the outer stream flushes and closes the whole chain.
FileOutputStreamtruncates by default. Passtrueto append.PushbackInputStreamlets you peek by unreading bytes. Keep a separate reference if you also stack a data stream on it.- You can write your own filters by extending
FilterInputStreamorFilterOutputStream.
Practice Questions
Why does new BufferedInputStream(new DataInputStream(new FileInputStream(f))) not let you call readInt()?
The outermost object is a BufferedInputStream, which has only the basic read methods. To call readInt, the DataInputStream must be the outermost layer, wrapping the buffered stream: new DataInputStream(new BufferedInputStream(new FileInputStream(f))).
In a chain of three streams, which one do you close?
Only the outermost one. Each filter's close flushes if needed and closes the stream it wraps, so the whole chain is closed.
A log file loses its old contents every time the program starts. What's the fix?
Open it in append mode: new FileOutputStream("app.log", true). The one-argument constructor truncates the file.
You read two bytes from a PushbackInputStream with buffer size 2, then want to put them back so the next read returns the first one. In what order do you call unread?
Unread the second byte first, then the first: pin.unread(b2); pin.unread(b1);. The pushback buffer works like a stack, so the last byte unread is the first one read again.
Write the chain for reading doubles from a gzip-compressed file, with buffering.
new DataInputStream(new BufferedInputStream(new GZIPInputStream(new FileInputStream("data.gz")))). GZIPInputStream has its own internal buffer for compressed input, but the outer BufferedInputStream makes the small reads of readDouble efficient on the decompressed data.
Previous: Java I/O Streams: Reading and Writing Bytes
Next: Java Text Input and Output: PrintWriter, BufferedReader and Saving Objects as Text
Related reading
- Java I/O Streams: Reading and Writing Bytes
- Java Parallel Streams: When They Help, Ordering and Thread Safety
- Java Primitive Streams: IntStream, LongStream and DoubleStream
- Implementing Java Stream Gatherers: Integrators, State, Short-Circuiting and Parallelism
- Java Stream Gatherers: windowFixed, windowSliding, fold, scan and mapConcurrent

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.