A useful feature for our histogram classes would be the capability
to save histogram data (including bin values, range, titles) to
a disk file and conversely to read histogram data from a file and
recreate the histogram from this data.
To rebuild an instance of the base class Histogram
we would need the bin array, the upper and lower range, the under
and over flow values, and also the text information such as the
title and axes labels. For the subclasses we would need additional
data values as well.
To provide histogram I/O there are several approaches to the
methods in the Histogram
class for all of the data fields necessary to save and rebuild
the histograms. An application method can then "get"
the data from a histogram and write the data to a file. Conversely,
an application could read in the data from the file and create
a new Histogram
object and fill its data fields with the values from the saved
histogram using the setter methods or via the arguments of a constructor.
- Stream Wrappers
A variation on the above approach is to create a new class (or
classes) whose only job is to write or read a histogram to/from
a file. Such a wrapper could use gettter/setter methods if available
or, if it has access
privileges, directly access the histogram class fields. For
example, if the fields are protected,
a wrapper in the same package can directly access the fields.
- Serialized Objects
The most elegant approach is simply to make the histogram classes
and save the histogram objects to a disk file by writing them
to an output object stream. To rebuild the histograms, just open
an input object stream to the file and read them in. We discussed
in Chapter 9: Java
: Object I/O the general techniques for creating and using
We demonstrate both the getter/setter and serialized object approaches.
The former approach illustrates some useful class design concepts
and it also has the advantage that we do not need to modify the
class or its subclasses in any way.
References & Web
Latest update: Nov. 14, 2004