Menu
Topics Index
...
`
PushbackReader is a character-stream reader that allows characters to be pushed back into the stream.

Constructors :
Constructor Description
PushbackReader(Reader in) Creates a new pushback reader with a one-character pushback buffer.
PushbackReader(Reader in, int size) Creates a new pushback reader with a pushback buffer of the given size.
Methods :
Method Description
boolean    ready() Tells whether this stream is ready to be read.
void    mark(int readAheadLimit) Marks the present position in the stream.
boolean    markSupported() Tells whether this stream supports the mark() operation, which it does not.
int    read() Reads a single character.
int    read(char[] cbuf, int off, int len) Reads characters into a portion of an array.
long    skip(long n) Skips characters.
void    unread(char[] cbuf) Pushes back an array of characters by copying it to the front of the pushback buffer.
void    unread(char[] cbuf, int off, int len) Pushes back a portion of an array of characters by copying it to the front of the pushback buffer.
void    unread(int c) Pushes back a single character by copying it to the front of the pushback buffer.
void    close() Closes the stream and releases any system resources associated with it.
Demo on PushbackReader
class PushbackReaderDemo
{
    public static void main(String[] args) throws IOException
    {
        byte[] array = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'};
        PushbackReader reader = new PushbackReader(new InputStreamReader(new ByteArrayInputStream(array)), array.length); // LINE A
        int j;
        while((j = reader.read()) != -1) // LINE B
        {
            System.out.print((char)j);    
        }
        
        for(int i = 0; i < array.length; i++)
        {
            reader.unread((int)(array[i])); // LINE C
        }
        
        System.out.println();
        j = 0;
        while((j = reader.read()) != -1)
        {
            System.out.print((char)j);    
        }
        reader.close(); //LINE D
    }

}
OUTPUT

Hello World
dlroW olleH

DESCRIPTION

In the above program at LINE A we created a PushbackReader for the InputStreamReader to read bytes of data. At LINE B we are reading data from reader. At LINE C we are unreading the bytes of data. When we unread characters the last unread character will be read first so we will get the data in the reverse order when we reread from reader.

THINGS TO TRY
  • Create a PushbackReader without specifying size and try to unread characters more than one to see an Pushback buffer overflow Exception. When we create a default PushbakReader we can unread only one character.
  • Comment LINE D and see the output. Output will be same since PushbackReader implements AutoCloseable.

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App