PushbackInputStream

PushbackInputStream allows a byte to be read and then returned to the stream. PushbackInputStream peeks what is coming from an input stream without disrupting it.

PushbackInputStream has the following constructors:

PushbackInputStream(InputStream inputStream)
creates a stream object that allows one byte to be returned to the input stream.
PushbackInputStream(InputStream inputStream, int numBytes)
creates a stream that has a pushback buffer that is numBytes long.

PushbackInputStream provides unread( ) method:

void unread(int ch)
pushes back the low-order byte of ch. This will be the next byte returned by a subsequent call to read( ).
void unread(byte buffer[ ])
returns the bytes in buffer.
void unread(byte buffer, int offset, int numChars)
pushes back numChars bytes beginning at offset from buffer.

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PushbackInputStream;

public class Main {
  public static void main(String args[]) throws IOException {
    byte buf[] = "==  = ".getBytes();
    PushbackInputStream f = new PushbackInputStream(new ByteArrayInputStream(buf));
    int c;
    while ((c = f.read()) != -1) {
      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