JavaPushbackReader

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Java PushbackReader Class

Java PushbackReader class is a character stream reader. It is used to pushes back a character into stream and overrides the FilterReader class.

Class declaration

Let' s see the declaration for java.io.PushbackReader class:

  1. public class PushbackReader extends FilterReader  

Class Methods

Method

Description

int read()

It is used to read a single character.

void mark(int readAheadLimit)

It is used to mark the present position in a stream.

boolean ready()

It is used to tell whether the stream is ready to be read.

boolean markSupported()

It is used to tell whether the stream supports mark() operation.

long skip(long n)

It is used to skip the character.

void unread (int c)

It is used to pushes back the character by copying it to the pushback buffer.

void unread (char[] cbuf)

It is used to pushes back an array of character by copying it to the pushback buffer.

void reset()

It is used to reset the stream.

void close()

It is used to close the stream.

Example of PushbackReader class

  1. import java.io.*;  
  2. public class ReaderExample{  
  3.     public static void main(String[] args) throws Exception {  
  4.         char ary[] = {'1','-','-','2','-','3','4','-','-','-','5','6'};  
  5.         CharArrayReader reader = new CharArrayReader(ary);   
  6.         PushbackReader push = new PushbackReader(reader);  
  7.         int i;  
  8.             while( (i = push.read())!= -1) {  
  9.                 if(i == '-') {  
  10.                     int j;  
  11.                     if( (j = push.read()) == '-'){  
  12.                          System.out.print("#*");  
  13.                     }else {  
  14.                         push.unread(j); // push back single character  
  15.                         System.out.print((char)i);  
  16.                     }  
  17.                 }else {  
  18.                         System.out.print((char)i);  
  19.                 }  
  20.            }         
  21.     }  
  22. }  

Output

  1. 1#*2-34#*-56