Java Reference
In-Depth Information
The buffer size that you get by default when you call the constructor in the previous code fragment is
2048 bytes. This will be 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.
Deciding on a suitable size for a buffer is a matter of judgment. You need to think about how the buffer
size will affect operations in your program. The total amount of data involved as well as the amount that
you need to process at one time also come into it. For instance, you will usually want to choose a buffer
size that is a multiple of the amount of data that your program will request in each read operation.
Suppose you expect your program to read and process 600 bytes at a time for instance. In this case you
should choose a buffer size that is a multiple of 600 bytes. The multiple, and therefore the total buffer
size, is a balance between the amount of memory required for the buffer and its effect on the efficiency
of your program. If you expect to be processing 100 sets of data, each of 600 bytes, you might settle on
a buffer size of 6000 bytes as a reasonable choice. Each buffer-full would then consist of 10 sets of data,
and there would only need to be ten physical read operations to refill the buffer.
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 the diagram below:
OutputStream
FileOutputStream
ByteArrayOutputStream
For Writing to a File
For Writing to a byte Array
ObjectOutputStream
PipedOutputStream
For Writing Objects to a Stream
For Writing to a Piped Stream
FilterOutputStream
For filtering Output from
an Existing Stream
We will be using the FileOutputStream class that is derived from OutputStream when we write
files in the next chapter, and will investigate the methods belonging to the ObjectOutputStream
class in Chapter 12 Serializing Objects , when we learn how to write objects to a file.
Note that this is not the complete set of output stream classes. The FilterOutputStream has a further
seven subclasses, including the BufferedOutputStream class that does for output streams what the
BufferedInputStream class does for input streams. There is also the PrintStream class, which we will
be looking at a little later in this chapter, since output to the command line is via a stream object of this type.
Search WWH ::




Custom Search