Appending to a File Used for Serialization
I was reading on Serialization and I started playing with it. Then I wondered if it was possible to serialize the same object again in the same file but different times. Here is an example:
This class will be our perpetual class.
Code:
import java.io.Serializable;
import java.util.Date;
public class PersistentTime implements Serializable {
private Date time1;
public PersistentTime() {
time1 = new Date();
}
public Date getTime() {
return time1;
}
}
Run the idiom below twice so four PersistentTime objects are be conserved. (Only two are saved I think) Wait two seconds between the first and second run because there is a Thread.sleep() in it.
Code:
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
public class FlattenTime {
public static void main(String[] args) throws Exception {
String filename = "time.ser";
PersistentTime time = new PersistentTime();
Thread.sleep(1000);
PersistentTime time1 = new PersistentTime();
FileOutputStream fos = null;
ObjectOutputStream out = null;
fos = new FileOutputStream(filename, true);
out = new ObjectOutputStream(fos);
out.writeObject(time);
out.writeObject(time1);
out.close();
}
}
The code below reads the 4 objects (only reading 2).
Code:
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.Date;
public class InflateTime {
public static void main(String[] args) throws Exception {
String filename = "time.ser";
PersistentTime time1 = null, time2 = null, time3 = null, time4 = null;
FileInputStream fis;
ObjectInputStream in;
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
time1 = (PersistentTime) in.readObject();
time2 = (PersistentTime) in.readObject();
time3 = (PersistentTime) in.readObject();
time4 = (PersistentTime) in.readObject();
System.out.println("Current Time: " + new Date());
System.out.println("Flattened Time #1: " + time1.getTime());
System.out.println("Flattened Time #2: " + time2.getTime());
System.out.println("Flattened Time #3: " + time3.getTime());
System.out.println("Flattened Time #4: " + time4.getTime());
}
}
Output:
Code:
Current Time: Sun Jan 31 14:56:11 CST 2010
Flattened Time #1: Sun Jan 31 14:55:58 CST 2010
Flattened Time #2: Sun Jan 31 14:56:00 CST 2010
Exception in thread "main" java.lang.NullPointerException
at InflateTime.main(InflateTime.java:29)
^As you can see, it's only reading two times, instead of four. :(
I have another question. Would it be better to wrap the FileInputStream and FileOutputStream into BufferedInputStream and BufferedOutputStream before sending it to the ObjectInputStream/ObjectOutputStream?
Like this:
Code:
fos = new FileOutputStream(filename, true);
out = new ObjectOutputStream(new BufferedOutputStream(fos));
If yes, why?
Any help is appreciated. Thanks in advance.