Java IO: PushbackReader

Connect with me:  
  Jenkov.com - News

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.

Here is a simple example:

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

int data = reader.read();

reader.unread(data);

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

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

This example sets an internal buffer of 8 characters. 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!