PushbackReader Java

PushbackReader Java is a character reader stream. It comes with the capability of pushing a character back to the stream. It is the only subclass of FilterReader.

Following is the class signature

public class PushbackReader extends FilterReader

Program that Pushes and Reads Using PushbackReader Java

The following program pushes a character back to the stream.

import java.io.*;
public class PRDemo
{
  public static void main(String args[]) throws IOException 
  {
    char carray[] = { 'q', 'u', 'a', 'l', 'i', 't', 'y' };
    CharArrayReader careader = new CharArrayReader(carray);
    PushbackReader preader = new PushbackReader(careader);
    
    int temp;
                                  // read first character and print
    temp = preader.read();
    System.out.println("The first character: " + (char) temp);
                                 // read the second character and print
    temp = preader.read();
    System.out.println("The second character: " + (char) temp);
                                 // read the third character and print
    temp = preader.read();
    System.out.println("The third character: " + (char) temp);

    preader.unread(temp);         // unread the third character
    	                           	          
    temp = preader.read();  	 // read it again and print
    System.out.println("Reading again third character: " + (char) temp);
   }
 }

PushbackReader Java

char carray[] = { ‘q’, ‘u’, ‘a’, ‘l’, ‘i’, ‘t’, ‘y’ };
CharArrayReader careader = new CharArrayReader(carray);
PushbackReader preader = new PushbackReader(careader, 3);

The character array carray is passed to CharArrayReader. The CharArrayReader object careader is passed to the constructor of PushbackReader constructor.

preader.unread(temp);

The character temp is unread (read back; internally file pointer moves back by one byte). Again reading with preader.read() method, reads the same character, here it is the third character 'a '.

Leave a Comment

Your email address will not be published.