go to previous page   go to home page   go to next page

Answer:

Yes, it is sometimes useful. The JDK class PushbackReader allows that. But our MyPushbackReader will not.


MyPushbackReader

MyPushbackReader works like this: An instance variable, isPushBack, is true when there is a pushed-back character. The next call to read() then returns the pushed-back character rather than a character from the input stream. Our read() returns -1 on end of file, which it gets from the read() method of BufferedReader. Recall that BufferedReader.read() returns an int that should be typecast into a char.

import java.io.* ;

class MyPushbackReader extends BufferedReader
{
  private int pushBack = ' ';
  private boolean isPushBack = false;

  public MyPushbackReader(Reader in)
  {
    super( in );
  }

  public int read() throws IOException
  {
    int chr;
    if ( isPushBack )
    {
      isPushBack = false;
      chr = pushBack;
      return chr;
    }
    chr = super.read();
    return chr;
  }

  public void unread( char c ) throws IOException
  {
    if ( isPushBack ) throw new IOException("Pushback buffer is full");
    pushBack   = (int)c;
    isPushBack = true;
  }
}

The unread() method pushes back one character by saving it in pushBack and setting isPushBack to true. If there already is a pushed-back character it throws an IOException, as does the unread() method in the JDK class PushbackReader.


QUESTION 7:

What does the following statement from the read() method do?

chr = super.read();