PushbackReader

In this chapter you will learn:

  1. How to use PushbackReader

Use 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.

import java.io.CharArrayReader;
import java.io.IOException;
import java.io.PushbackReader;
//from j a  v  a 2s. com
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;
      }
    }
  }
}

Next chapter...

What you will learn in the next chapter:

  1. What is Java Writer and how to use Writer