PushbackReader

The PushbackReader class allows one or more characters to be returned to the input stream. This allows you to peek in the input stream.

Here are its two constructors:

PushbackReader(Reader inputStream)
creates a buffered stream that allows one character to be pushed back.
PushbackReader(Reader inputStream, int bufSize)
the size of the pushback buffer is passed in bufSize.

PushbackReader unread( ) method returns one or more characters to the input stream.

It has the three forms shown here:

void unread(int ch)
pushes back the character ch. ch will be the character returned by a subsequent call to read( ).
void unread(char buffer[ ])
push back the characters in buffer.
void unread(char buffer[ ], int offset, int numChars)
pushes back numChars characters beginning at offset from buffer.
 
import java.io.CharArrayReader;
import java.io.IOException;
import java.io.PushbackReader;

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

    char buf[] = new char[s.length()];
    for(int i=0;i<s.length();i++){
      buf[i] = s.charAt(i);
    }
    CharArrayReader in = new CharArrayReader(buf);
    PushbackReader f = new PushbackReader(in);
    int c;
    while ((c = f.read()) != -1) {
      if(65535 == c){
        break;
      }
      switch (c) {
      case '=':
        c = f.read();
        if (c == '=')
          System.out.print(".eq.");
        else {
          System.out.print("=");
          f.unread(c);
        }
        break;
      default:
        System.out.print((char) c);
        break;
      }
    }
  }
}
  
Home 
  Java Book 
    File Stream