Java Reference
In-Depth Information
throws IOException , ClassNotFoundException {
in . defaultReadObject ();
unzipPrices ();
throws
}
protected
protected void
throws IOException {
ByteArrayOutputStream baos = new
void makeZippedPrices () throws
new ByteArrayOutputStream ();
GZIPOutputStream zip = new
new GZIPOutputStream ( baos );
ObjectOutputStream oos = new
new ObjectOutputStream (
new BufferedOutputStream ( zip ));
oos . writeObject ( prices );
oos . close ();
zip . close ();
zippedPrices = baos . toByteArray ();
new
}
protected
protected void
void unzipPrices ()
throws
throws IOException , ClassNotFoundException {
ByteArrayInputStream bais = new
new ByteArrayInputStream ( zippedPrices );
GZIPInputStream zip = new
new GZIPInputStream ( bais );
ObjectInputStream ois = new
new ObjectInputStream (
new BufferedInputStream ( zip ));
prices = ( SortedMap < Date , StockPrice >) ois . readObject ();
ois . close ();
zip . close ();
new
}
}
The zipPrices() method serializes the map of prices to a byte array and saves the resulting
bytes, which are then serialized normally in the writeObject() method when it calls the
defaultWriteObject() method. (In fact, as long as the serialization is being customized, it
will be ever-so-slightly better to make the zippedPrices array transient, and write out its
length and bytes directly. But this example code is a little clearer, and simpler is better.) On
deserialization, the reverse operation is performed.
If the goal is to serialize to a byte stream (as in the original sample code), this is a losing pro-
position. That isn't surprising; the time required to compress the bytes is much longer than
the time to write them to a local byte array. Those times are shown in Table 10-12 .
Search WWH ::




Custom Search