Java Reference
In-Depth Information
implement the Serializable interface. There are no methods in the interface;
one must simply declare that a class is serializable. 6 The GZIPOutputStream
wraps an OutputStream and compresses the writes prior to sending it to the
OutputStream . In addition, there is a BufferedOutputStream class. Similar wrappers
are found on the InputStream side. As an example, suppose we have an array of
serializable Person objects. We can write the objects, as a unit, compressed as
follows:
Person [ ] p = getPersons( ); // populate the array
FileOutputStream fout = new FileOutputStream( "people.gzip" );
BufferedOutputStream bout = new BufferedOutputStream( fout );
GZIPOutputStream gout = new GZIPOutputStream( bout );
ObjectOutputStream oout = new ObjectOutputStream( gout );
oout.writeObject( p );
oout.close( );
Later on, we could read everything back:
FileInputStream fin = new FileInputStream( "people.gzip" );
BufferedInputStream bin = new BufferedInputStream( fin );
GZIPInputStream gin = new GZIPInputStream( bin );
ObjectInputStream oin = new ObjectInputStream( gin );
Person [ ] p = (Person[ ]) oin.readObject( );
oin.close( );
The online code expands this example by having each Person store a name, a
birth date, and the two Person objects that represent the parents.
The idea of nesting wrappers in order to add functionality is known as
the decorator pattern . By doing this, we have numerous small classes that
are combined to provide a powerful interface. Without this pattern, each
different I/O source would have to have functionality for compression,
serialization, character, and byte I/O, and so on. With the pattern, each
source is only responsible for minimal, basic I/O, and then the extra fea-
tures are added on by the decorators.
The idea of nesting
wrappers in order
to add functionality
is known as the
decorator pattern .
6. The reason for this is that serialization, by default, is insecure. When an object is written out
in an ObjectOutputStream , the format is well known, so its private members can be read by a
malicious user. Similarly, when an object is read back in, the data on the input stream is not
checked for correctness, so it is possible to read a corrupt object. There are advanced tech-
niques that can be used to ensure security and integrity when serialization is used, but that is
beyond the scope of this text. The designers of the serialization library felt that serialization
should not be the default because correct use requires knowledge of these issues, and so
they placed a small roadblock in the way.
 
 
Search WWH ::




Custom Search