Java I/O: The Byte-Oriented Stream Classes
the previous posts, we got an introduction to byte-oriented stream classes,
where we used the
we can see from I/O class hierarchy diagram below, there are several more
classes in this category. Although it is not possible to cover all these
classes all togehter, we will look at how to use some of them in practical
situations so that we are able to use the rest in our applications. We begin
As the names suggest, the first two classes operate
on a byte
array and the latter two operate on object data—rather than primitive data types.
These are obviously the decorator classes that
wrap the InputStream/OutputStream base classes i.e. These classes decorate the
InputStream and OutputStream based on the well-known Decorator design pattern.
discuss the purpose behind having them in the first place. In many situations,
we have the data available in byte arrays. For example, when we transmit
and receive data over a modem, the data is available in modem buffers, which are basically
the byte arrays.
the case of the NYSE and NASDAQ.
These stock exchanges stream
trade data in real time to brokers.
Trade data consists of scrip
code, trade time, bid price, offer price, volume, the high, low, and opening
prices, as well as a few more fields.
This data is transmitted
over a socket connection to the client machine.
The exchange server writes
this data to a modem buffer. The data is sent in raw binary format in order to
In this case, we would use a ByteArrayOutputStream class to write
the data to its internal buffer. This class deals with only raw binary data. To
provide the abstraction to higher data types, we would use the DataOutputStream class, which is a
wrapper on the ByteArrayOutputStream
DataOutputStream contains many methods to write the primitive data types. By
chaining the data output stream to a byte array output stream, we can write the
binary form of the trade data into a byte array and then send the entire array
in a single packet to the remote machine.
At the client end, we would use ByteArrayInputStream to buffer the data
retrieved from a socket connection. You would then use the DataInputStream class to convert the raw data to primitive data
is an important point to notice here that, The DataInputStream and DataOutputStream
go together. If the data is written using any other output stream class, the
read methods of the DataInputStream
will not be able to successfully read the data.