Java PushbackInputStream class

Introduction

PushbackInputStream can read a byte read and return it to the stream.

PushbackInputStream has the following constructors:

PushbackInputStream(InputStream inputStream)  
PushbackInputStream(InputStream inputStream, int numBytes) 

PushbackInputStream provides unread(), shown here:

void unread(int  b)  
void unread(byte  buffer [ ])  
void unread(byte  buffer, int offset, int numBytes) 

Here is an example shows how to create a programming language parser via PushbackInputStream and unread().

// Demonstrate unread(). 
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PushbackInputStream;

public class Main {
  public static void main(String args[]) {
    String s = "if (a == 4) a = 0;\n";
    byte buf[] = s.getBytes();
    ByteArrayInputStream in = new ByteArrayInputStream(buf);
    int c;//from w  w w .  j a v  a  2 s.  co  m

    try (PushbackInputStream f = new PushbackInputStream(in)) {
      while ((c = f.read()) != -1) {
        switch (c) {
        case '=':
          if ((c = f.read()) == '=')
            System.out.print(".eq.");
          else {
            System.out.print("<-");
            f.unread(c);
          }
          break;
        default:
          System.out.print((char) c);
          break;
        }
      }
    } catch (IOException e) {
      System.out.println("I/O Error: " + e);
    }
  }
}



PreviousNext

Related