Chapter 19: Input/Output: Exploring java.io 569
When you run the program, you will create the following output. Notice how after the call
toreset( ), the threeX’s end up at the beginning.
Buffer as a string
This should end up in the array
Into array
This should end up in the array
To an OutputStream()
Doing a reset
XXX
This example uses thewriteTo( )convenience method to write the contents offtotest.txt.
Examining the contents of thetest.txtfile created in the preceding example shows the result
we expected:
This should end up in the array
Filtered Byte Streams
Filtered streamsare simply wrappers around underlying input or output streams that
transparently provide some extended level of functionality. These streams are typically
accessed by methods that are expecting a generic stream, which is a superclass of the
filtered streams. Typical extensions are buffering, character translation, and raw data
translation. The filtered byte streams areFilterInputStreamandFilterOutputStream. Their
constructors are shown here:
FilterOutputStream(OutputStreamos)
FilterInputStream(InputStreamis)
The methods provided in these classes are identical to those inInputStreamandOutputStream.
Buffered Byte Streams
For the byte-oriented streams, abuffered streamextends a filtered stream class by attaching
a memory buffer to the I/O streams. This buffer allows Java to do I/O operations on more
than a byte at a time, hence increasing performance. Because the buffer is available, skipping,
marking, and resetting of the stream become possible. The buffered byte stream classes are
BufferedInputStreamandBufferedOutputStream.PushbackInputStreamalso implements
a buffered stream.
BufferedInputStream
Buffering I/O is a very common performance optimization. Java’sBufferedInputStreamclass
allows you to “wrap” anyInputStreaminto a buffered stream and achieve this performance
improvement.
BufferedInputStreamhas two constructors:
BufferedInputStream(InputStreaminputStream)
BufferedInputStream(InputStreaminputStream, intbufSize)
The first form creates a buffered stream using a default buffer size. In the second, the size
of the buffer is passed inbufSize.Use of sizes that are multiples of a memory page, a disk