Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Chapter 19: Input/Output: Exploring java.io 585


default:
if (!marked)
System.out.print((char) c);
break;
}
}
}
}


BufferedWriter


ABufferedWriteris aWriterthat buffers ouput. Using aBufferedWritercan increase
performance by reducing the number of times data is actually physically written to the
output stream.
ABufferedWriterhas these two constructors:


BufferedWriter(WriteroutputStream)
BufferedWriter(WriteroutputStream, intbufSize)

The first form creates a buffered stream using a buffer with a default size. In the second, the
size of the buffer is passed inbufSize.


PushbackReader


ThePushbackReaderclass 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(ReaderinputStream)
PushbackReader(ReaderinputStream, intbufSize)

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 inbufSize.
PushbackReaderprovidesunread( ), which returns one or more characters to the invoking
input stream. It has the three forms shown here:


void unread(intch)
void unread(charbuffer[ ])
void unread(charbuffer[ ], intoffset, intnumChars)

The first form pushes back the character passed inch.This will be the next character returned
by a subsequent call toread( ). The second form returns the characters inbuffer.The third
form pushes backnumCharscharacters beginning atoffsetfrombuffer.AnIOExceptionwill
be thrown if there is an attempt to return a character when the pushback buffer is full.
The following program reworks the earlierPushBackInputStreamexample by replacing
PushBackInputStreamwith aPushbackReader. 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";

Free download pdf