Java Reference
In-Depth Information
You can close an InputStream by calling its close() method. After you have closed an input stream,
subsequent attempts to access or read from the stream cause an IOException to be thrown because the
close() operation has released the resources held by the stream object, including the source of the data,
such as a file. I discuss closing a stream in more detail in Chapter 9.
Buffered Input Streams
The BufferedInputStream class defines an input stream that is buffered in memory and thus makes
read operations on the stream more efficient. The BufferedInputStream is derived from the FilterIn-
putStream class, which has InputStream as a base.
You create a BufferedInputStream object from another input stream, and the constructor accepts a ref-
erence of type InputStream as an argument. The BufferedInputStream class overrides the methods in-
herited from InputStream so that operations are via a buffer; it implements the abstract read() method.
Here's an example of how you create a buffered input stream:
BufferedInputStream keyboard = new BufferedInputStream(System.in);
The argument System.in is an InputStream object that is a static member of the System class and en-
capsulates input from the keyboard. You look into how you can read input from the keyboard a little later in
this chapter.
The effect of wrapping a stream in a BufferedInputStream object is to buffer the underlying stream
in memory so that data can be read from the stream in large chunks — up to the size of the buffer that is
provided. The data is then made available to the read() methods directly from the buffer in memory and
the buffer is replenished automatically. A real read operation from the underlying stream is executed only
when the buffer is empty.
With a suitable choice of buffer size, the number of input operations from the underlying stream that are
needed is substantially reduced, and the process is a whole lot more efficient. This is because for many input
streams, each read operation carries quite a bit of overhead, beyond the time required to actually transfer the
data. The buffer size that you get by default when you call the BufferedInputStream constructor as in the
previous code fragment is 8192 bytes. This is adequate for most situations where modest amounts of data
are involved. The BufferedInputStream class also defines a constructor that accepts a second argument of
type int that enables you to specify the size in bytes of the buffer to be used.
Basic Output Stream Operations
The OutputStream class contains three write() methods for writing binary data to the stream. As can be
expected, these mirror the read() methods of the InputStream class. This class is also abstract, so only
subclasses can be instantiated. The principal direct subclasses of OutputStream are shown in Figure 8-3 .
FIGURE 8-3
 
 
Search WWH ::




Custom Search