So far we have seen that we can do I/O with primitive
data types and also with String
objects. With the ObjectInputStream
and ObjectOutputStream
you can, in fact, do I/O with other types of objects as well.
The writeObject
(Object) method in ObjectOutputStream
grabs the data from the class fields of an existing object and sends
that data through the stream. Similarly, the readObject()
method in ObjectInputStream
can read this data from its stream and fill the data fields in a
new instance of the class.
The data is sent sequentially, or serially, a byte
at a time on the stream and so this process is also referred to
as serialization.
For a class to work with these methods, it must implement
the Serializable
interface. This interface has no methods but tags the class as suitable
for serializing. There are, for example, security concerns with
regard to I/O with objects since the internal data of an object
could become exposed during the transfer. So not all classes are
suitable for serializing.
Many core language classes implement Serializable
but you should check the Java 2 API specifications to make sure
for a particular class of interest.
Within a class there may be data that is only temporary,
that is, the values are only useful for a short time during the
running of a program and don't need to be saved. These data fields
can be labeled transient
and will not be included in the serialization.
When an object to be serialized holds references to
other objects, those objects will also be serialized if they implement
Serializable.
Otherwise, they should be labeled transient.
So a class for serializing could look as follows:
public class MyClass implements Serializable {
int fI,fJ;
double fValue
transient int fTmpValue;
String fTitle;
OtherClass fOtherClass;
... constructors & methods ...
}
Instances of this class could be saved to a file using
a method such as this:
static
public void saveMyClass (MyClass my_object, File file) {
FileOutputStream file_out = new FileOutputStream
(file);
ObjectOutputStream obj_out_stream = new
ObjectOutputStream (file_out);
obj_out_stream.writeObject (my_object);
obj_out_stream.close ();
}
Similarly, to read the object back in from a file
we could use a method as follows:
static
public MyClass getMyClass (File file) {
FileInputStream file_in = new FileInputStream
(file);
ObjectInputStream obj_in_stream = new ObjectInputStream
(file_in);
MyClass my_obj = (MyClass)(obj_in_stream.readObject
());
obj_in_stream.close ();
return my_obj;
}
There are a number of other issues regarding serialization
that are beyond the scope of this chapter and book. (See references.)
See the Chapter 9:
Tech section for an example of object I/O with our histogram
class objects.
References & Web
Resources
Latest update: Nov. 14, 2004
|