Tech and Media Labs
This site uses cookies to improve the user experience.

Java IO: PushbackInputStream

Jakob Jenkov
Last update: 2015-08-29

The PushbackInputStream is intended to be used when you parse data from an InputStream. Sometimes you need to read ahead a few bytes to see what is coming, before you can determine how to interpret the current byte. The PushbackInputStream allows you to do that. Well, actually it allows you to push the read bytes back into the stream. These bytes will then be read again the next time you call read().

PushbackInputStream Example

Here is a simple PushbackInputStream example:

PushbackInputStream input = new PushbackInputStream(
                                new FileInputStream("c:\\data\\input.txt"));

int data =;


The call to read() reads a byte just like from an InputStream. The call to unread() pushes a byte back into the PushbackInputStream. The next time read() is called the pushed back bytes will be read first. If you push back multiple bytes into the PushbackInputStream, the latest byte pushed back will be returned first from read(), just like on a stack.

Setting the Push Back Limit of a PushbackInputStream

You can set the number of bytes you should be able to unread in the constructor of the PushbackInputStream. Here is how to set the push back limit via the PushbackInputStream constructor:

int pushbackLimit = 8;
PushbackInputStream input = new PushbackInputStream(
                                new FileInputStream("c:\\data\\input.txt"),

This example sets an internal buffer of 8 bytes. That means you can unread at most 8 bytes at a time, before reading them again.

Jakob Jenkov

Copyright  Jenkov Aps
Close TOC