Beyond the familiar methods ofInputStream,PushbackInputStreamprovidesunread( ),
shown here:
void unread(intch)
void unread(bytebuffer[ ])
void unread(bytebuffer, intoffset, intnumChars)
The first form pushes back the low-order byte ofch.This will be the next byte returned by a
subsequent call toread( ). The second form returns the bytes inbuffer.The third form pushes
backnumCharsbytes beginning atoffsetfrombuffer.AnIOExceptionwill be thrown if there
is an attempt to return a byte when the pushback buffer is full.
Here is an example that shows how a programming language parser might use a
PushbackInputStreamandunread( )to deal with the difference between the= =operator
for comparison and the=operator for assignment:
// Demonstrate unread().
import java.io.*;
class PushbackInputStreamDemo {
public static void main(String args[]) throws IOException {
String s = "if (a == 4) a = 0;\n";
byte buf[] = s.getBytes();
ByteArrayInputStream in = new ByteArrayInputStream(buf);
PushbackInputStream f = new PushbackInputStream(in);
int c;
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;
}
}
}
}
Here is the output for this example. Notice that==was replaced by“.eq.”and=was replaced
by“<–”.
if (a .eq. 4) a <- 0;
CAUTIONAUTION PushbackInputStreamhas the side effect of invalidating themark( )orreset( )
methods of theInputStreamused to create it. UsemarkSupported( )to check any stream
on which you are going to usemark( )/reset( ).
572 Part II: The Java Library