PushbackReader sample program in Java

By: Daniel Malcolm Viewed: 149 times  Printer Friendly Format    


The PushbackReader class allows one or more characters to be returned to the input stream. This allows you to look ahead in the input stream. Here are its two constructors:

PushbackReader(Reader inputStream)
PushbackReader(Reader inputStream, int bufSize)


The first form creates a buffered stream that allows one character to be pushed back. In the second, the size of the pushback buffer is passed in bufSize. PushbackReader provides unread( ), which returns one or more characters to the invoking input stream. It has the three forms shown here:

void unread(int ch)
void unread(char buffer[ ])
void unread(char buffer[ ], int offset, int numChars)

The first form pushes back the character passed in ch. This will be the next character returned by a subsequent call to read( ). The second form returns the characters in buffer. The third form pushes back numChars characters beginning at offset from buffer. An IOException will be thrown if there is an attempt to return a character when the pushback buffer is full.

The following program reworks the earlier PushBackInputStream example by replacing 
PushBackInputStream
with a PushbackReader. As before, it shows how a programming language parser can use a pushback stream to deal with the difference between the == operator for comparison and the = operator for assignment.

// Demonstrate unread().
import java.io.*;
class PushbackReaderDemo {
public static void main(String args[]) throws IOException {
String s = "if (a == 4) a = 0;\\n";
char buf[] = new char[s.length()];
s.getChars(0, s.length(), buf, 0);
CharArrayReader in = new CharArrayReader(buf);
PushbackReader f = new PushbackReader(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;
}
}
}
}

This tutorial is an extract from the "The Complete Reference Part 2 by Herbert Schildt".



Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial