Java Reference
In-Depth Information
The readObject() method from ObjectInputStream can read this data
from the stream and fill the data fields in a new instance of the class.
The data is sent sequentially, or serially ,abyte at a time on the stream, 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 is intended to tag the class as suitable for serializing. There are, for example,
security concerns with regard to this process since internal data of an object may
become vulnerable as it travels through the I/O system. 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. 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 like the following:
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;
}
Search WWH ::




Custom Search