Serializating Objects
SerializeTest.java
ObjectOutputStream will serialize any Object that implments the
marker interface Serializable.
« Interface »
Serializable
|
Not only that, but if an object contains references to other Serializable objects,
ObjectOutputStream serializes them too, and preserves the links.
ObjectOutputStream
|
+ ObjectOutputStream( OutputStream )
+ writeObject(Object)
|
When the root object is de-serialized, ObjectInputStream de-serializes
all referenced objects as well, and restores the links.
ObjectInputStream
|
+ ObjectInputStream( InputStream )
+ readObject() : Object
|
Thus serialization allows us to save and restore data structures of arbitrary complexity.
|
import java.io.*;
import java.util.*;
public class SerializeTest {
public static void main(String[] args) throws Exception {
List list, copy;
list = Arrays.asList(new File(".").listFiles());
serializeObject(list);
copy = (List) deserializeObject();
System.out.println("list.equals(copy): " + list.equals(copy));
}
static void serializeObject(Object obj) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("data.ser"));
oos.writeObject(obj);
oos.close();
}
static Object deserializeObject() throws Exception {
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream("data.ser"));
Object object = ois.readObject();
ois.close();
return object;
}
}
|
|