Writing to an OutputStream
with FilterOutputStream
The complement to DataInputStream is DataOutputStream, which formats each of the primitive types and String objects onto a stream in such a way that any DataInputStream, on any machine, can read them. All the methods start with write, such as writeByte( ), writeFloat( ), etc.
The original intent of PrintStream was to print all of the primitive data types and String objects in a viewable format. This is different from DataOutputStream, whose goal is to put data elements on a stream in a way that DataInputStream can portably reconstruct them.
The two important methods in PrintStream are print( ) and println( ), which are overloaded to print all the various types. The difference between print( ) and println( ) is that the latter adds a newline when its done.
PrintStream can be problematic because it traps all IOExceptions (You must explicitly test the error status with checkError( ), which returns true if an error has occurred). Also, PrintStream doesnt internationalize properly and doesnt handle line breaks in a platform-independent way (these problems are solved with PrintWriter, described later).
BufferedOutputStream is a modifier and tells the stream to use buffering so you dont get a physical write every time you write to the stream. Youll probably always want to use this when doing output.
Table 12-4. Types of FilterOutputStream
|
Class
|
Function
|
Constructor Arguments
|
|
How to use it
|
|
Data-OutputStream
|
Used in concert with DataInputStream so you can write primitives (int, char, long, etc.) to a stream in a portable fashion.
|
OutputStream
|
|
Contains full interface to allow you to write primitive types.
|
|
PrintStream
|
For producing formatted output. While DataOutputStream handles the storage of data, PrintStream handles display.
|
OutputStream, with optional boolean indicating that the buffer is flushed with every newline.
|
|
Should be the final wrapping for your OutputStream object. Youll probably use this a lot.
|
|
Buffered-OutputStream
|
Use this to prevent a physical write every time you send a piece of data. Youre saying Use a buffer. You can call flush( ) to flush the buffer.
|
OutputStream, with optional buffer size.
|
|
This doesnt provide an interface per se, just a requirement that a buffer is used. Attach an interface object.
|