Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

586 Part II: The Java Library


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;
}
}
}
}

PrintWriter


PrintWriteris essentially a character-oriented version ofPrintStream. It implements the
Appendable,Closeable, andFlushableinterfaces.PrintWriterhas several constructors.
The following have been supplied byPrintWriterfrom the start:

PrintWriter(OutputStreamoutputStream)
PrintWriter(OutputStreamoutputStream, booleanflushOnNewline)

PrintWriter(WriteroutputStream)
PrintWriter(WriteroutputStream, booleanflushOnNewline)

Here,outputStreamspecifies an openOutputStreamthat will receive output. TheflushOnNewline
parameter controls whether the output buffer is automatically flushed every timeprintln( ),
printf( ),orformat( )is called. IfflushOnNewlineistrue, flushing automatically takes place. If
false, flushing is notautomatic. Constructors that do not specify theflushOnNewlineparameter
do not automatically flush.
The next set of constructors give you an easy way to construct aPrintWriterthat writes its
output to a file.

PrintWriter(FileoutputFile) throws FileNotFoundException
PrintWriter(FileoutputFile, StringcharSet)
throws FileNotFoundException, UnsupportedEncodingException

PrintWriter(StringoutputFileName) throws FileNotFoundException
PrintWriter(StringoutputFileName, StringcharSet)
throws FileNotFoundException, UnsupportedEncodingException
Free download pdf