Tutorials About

Java IO: PushbackReader

Last updated: 2015-08-29

The PushbackReader is intendended to be used when you parse data from a Reader. Sometimes you need to read ahead a few characters to see what is coming, before you can determine how to interprete the current character. The PushbackReader allows you to do that. Well, actually it allows you to push back the read characters into the Reader. These characters will then be read again the next time you call read().

The PushbackReader works much like the PushbackInputStream except that the PushbackReader works on characters, whereas the PushbackInputStream works on bytes.

PushbackReader Example

Here is a simple PushbackReader example:

PushbackReader reader = new PushbackReader(
                                new FileReader("c:\\data\\input.txt"));

int data =;


The call to read() reads a character from the PushbackReader just like from any other Reader. The call to unread() pushes a character back into the PushbackReader. The next time read() is called the pushed back characters will be read first. If you push back multiple characters into the PushbackReader, the latest pushed back character will be returned first from the read() method, just like with a stack.

Setting the Push Back Limit of a PushbackReader

You can set the number of characters you should be able to unread in the constructor of the PushbackReader. Here is how to set the pushback limit using the PushbackReader constructor:

int pushbackLimit = 8;    
PushbackReader reader = new PushbackReader(
                                new FileReader("c:\\data\\input.txt"),

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

Connect with me: Newsletter - Get all my free tips!

Close TOC
This website uses cookies to improve the user experience and gather statistics. Our advertisers use cookies too (3rd party cookies), to provide more relevant ads. Continued use of this website implies that you accept the use of cookies on this website. We do not share our cookies with our advertisers, and our advertisers do not share cookies with us.