574 Part II: The Java Library
}
input.close();
}
}
This example creates aVectorand then adds two filenames to it. It passes that vector of
names to theInputStreamEnumeratorclass, which is designed to provide a wrapper on the
vector where the elements returned are not the filenames but rather, openFileInputStreams
on those names. TheSequenceInputStreamopens each file in turn, and this example prints
the contents of the two files.
PrintStream
ThePrintStreamclass provides all of the output capabilities we have been using from the
Systemfile handle,System.out, since the beginning of the book. This makesPrintStream
one of Java’s most often used classes. It implements theAppendable,Closeable, and
Flushableinterfaces.
PrintStreamdefines several constructors. The ones shown next have been specified
from the start:
PrintStream(OutputStreamoutputStream)
PrintStream(OutputStreamoutputStream, booleanflushOnNewline)
PrintStream(OutputStreamoutputStream, booleanflushOnNewline,
StringcharSet)
Here,outputStreamspecifies an openOutputStreamthat will receive output. TheflushOnNewline
parameter controls whether the output buffer is automatically flushed every time a newline
(\n) character or a byte array is written, or whenprintln( )is called. IfflushOnNewlineis
true, flushing automatically takes place. If it isfalse, flushing is not automatic. The first
constructor does not automatically flush. You can specify a character encoding by passing
its name incharSet.
The next set of constructors give you an easy way to construct aPrintStreamthat writes
its output to a file.
PrintStream(FileoutputFile) throws FileNotFoundException
PrintStream(FileoutputFile, StringcharSet)
throws FileNotFoundException, UnsupportedEncodingException
PrintStream(StringoutputFileName) throws FileNotFoundException
PrintStream(StringoutputFileName, StringcharSet)
throws FileNotFoundException, UnsupportedEncodingException
These allow aPrintStreamto be created from aFileobject or by specifying the name of a
file. In either case, the file is automatically created. Any preexisting file by the same name is
destroyed. Once created, thePrintStreamobject directs all output to the specified file. You
can specify a character encoding by passing its name incharSet.
PrintStreamsupports theprint( )andprintln( )methods for all types, includingObject.
If an argument is not a primitive type, thePrintStreammethods will call the object’stoString( )
method and then display the result.