Menu
Topics Index
...
`

Demo on PushbackReader - Java Example Program


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.

© meritcampus 2019

All Rights Reserved.

Open In App