Java PushbackReader Class with Examples

Java is wide range and used in various applications.

PushbackReader is discussed in a detailed manner. It allows characters to be pushed back into the Stream. The unread() method of this class allows us to pushback the characters.

Explanation of Java PushbackReader Class:

  • A character stream reader is the Java PushbackReader class.
  • It overrides the FilterReader class and pushes a character back into the stream.
  • Pushing characters back into the stream is possible with this class, which is a character stream class.
  • The characters can be pushed back using this class’s unread() function.

Pushback explanation:

  • A byte can be received from an input stream and then “pushed back”—that is, returned to the stream—by using pushback.
  • The PushbackInputStream class puts this concept into practice. It offers a way to “peek” into data coming from an input stream without interfering with it.

How to create Java PushbackReader:

  • You must first build an instance of a Java PushbackReader before you can utilize it.
  • By utilizing the new operator in ordinary object instantiation, you can create a PushbackReader.
  • A Java Reader is required to be passed to the PushbackReader constructor in order for it to read the characters.
PushbackReader pushbackReader =
    new PushbackReader(new FileReader(" "))

Declaration:

public class PushbackReader extends FilterReader

Parameter:

  • C is the int value of the character that has to be pushed back.

Return Value:
It does not return any Value

Exception:

  • IOException − When an I/O error occurs or the pushback buffer fills up.

Read characters:

It used to read the characters of pushbackreader:

int aChar = pushbackReader.read();
while(aChar != -1) {
    System.out.println((char) aChar);
    aChar = pushbackReader.read();
}

Class Methods:

Method Description
int read() It reads one character at a time.
void mark(int readAheadLimit) It serves as a marker for the current location within a stream.
boolean ready() It is employed to determine when the stream is prepared for reading.
boolean markSupported() To find out if the stream supports the mark() action, use this.
long skip(long n) The character is skipped using it.
void unread (int c) By copying the character to the pushback buffer, it is utilized to push the character back.
void unread (char[] cbuf) It is used to push the character back by copying it to the pushback buffer.
void reset() The stream is reset using it.
void close() The stream is closed using it.

Constructor:

Constructor Description
PushbackReader(Reader in ) It creates a new pushback with one character pushback buffer.
PushbackReader (Reader in, int size) It creates a new pushback with pushback with given size.

Example 1:

import java.io.*;

public class TechVidvan {
    public static void main(String[] args) throws Exception {
        char ary[] = {'1', '-', '-', '2', '-', '3', '4', '-', '5'};
        CharArrayReader reader = new CharArrayReader(ary);
        PushbackReader push = new PushbackReader(reader);

        int i;
        while ((i = push.read()) != -1) {
            if (i == '-') {
                int j;
                if ((j = push.read()) == '-') {
                    System.out.print("#*");
                } else {
                    push.unread(j); // push back single character
                    System.out.print((char) i);
                }
            } else {
                System.out.print((char) i);
            }
        }
    }
}

Output:
1#*2-345

Example 2:

import java.io.*;

public class TechVidvan{
   public static void main(String[] args) {
      String s = "TechVidvan";

            StringReader sr = new StringReader(s);

            PushbackReader pr = new PushbackReader(sr, 20);

      try {
                  for (int i = 0; i < 5; i++) {
            char c = (char) pr.read();
            System.out.print("" + c);
         }

                  System.out.println();

                  pr.unread('A');

                  char c = (char) pr.read();

                  System.out.println("" + c);

                  pr.close();

      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}

Output:

TechV
A

Example 3:

import java.io.PushbackReader;
import java.io.StringReader;
public class TechVidvan
{
    public static void main(String args[])
    {
        try
        {  
            String str = “Welcome to TechVidvan Java Tutorials”; 
            StringReader reader = new StringReader(str); 
            PushbackReader pushbackReader = new PushbackReader(reader); 
            System.out.println("pushbackReader ready: " + pushbackReader.ready()); 
            for (int i = 0; i < 9; i++) 	
            { 
                char ch = (char) pushbackReader.read(); 
                System.out.print(ch); 
                pushbackReader.skip(1); 
            } 
        }
        catch (Exception e)	{  
            System.out.print("Error: "+e.toString());
        }  
    }
}

Output:
pushbackReader ready: true
Wloet ehi

Constructors:

  • PushbackReader(Reader push): Makes a new Pushback Reader and uses a character Pushback buffer to “push” it.
  • PushbackReader(Reader push, int size): Specifies the size of the pushback buffer when creating a new Pushback Reader.

Benefits:

  • One or more characters can be returned to the input stream using the PushbackReader class. You can now see into the input stream thanks to this.
  • generates a buffered stream that permits the pushing back of a single character. bufSize is the size of the pushback buffer that is passed.

Closing of PushBackReader:

  • It is important to remember to close the PushbackReader when you have completed reading the characters.
  • The Reader instance that a PushbackReader is reading from will also close when the PushbackReader is closed.
  • By using this to close: pushbackReader.close()

Conclusion

We have learned about the PushbackReader details. It is used as a pushbackreader in the stream. This feature is handy for parsing scenarios where you may need to backtrack in the input stream.