参考this:public class IDNMS{
public static void main(String[] args)throws IOException,ClassNotFoundException{
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream("datafile.txt"));
for(int i = 0; i < 5; i++){
data_Object data = new data_Object();
data.setData(i,"name" + i, "mymail" + i + "@earth.com");
out.writeObject(data);//write object first
}
out.close();
long now = System.currentTimeMillis();
while(System.currentTimeMillis() < now + 5000)
;//delay
ObjectInputStream in = new ObjectInputStream(
new FileInputStream("datafile.txt"));
for(int i = 0; i < 5; i++){
data_Object data = (data_Object)in.readObject();//read object
System.out.println(data);
}
in.close();
}
}
public static void main(String[] args)throws IOException,ClassNotFoundException{
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream("datafile.txt"));
for(int i = 0; i < 5; i++){
data_Object data = new data_Object();
data.setData(i,"name" + i, "mymail" + i + "@earth.com");
out.writeObject(data);//write object first
}
out.close();
long now = System.currentTimeMillis();
while(System.currentTimeMillis() < now + 5000)
;//delay
ObjectInputStream in = new ObjectInputStream(
new FileInputStream("datafile.txt"));
for(int i = 0; i < 5; i++){
data_Object data = (data_Object)in.readObject();//read object
System.out.println(data);
}
in.close();
}
}
使用缺省的serializetion的实现时,一个ObjectOutputStream的构造和一个ObjectInputStream的构造必须一一对应.ObjectOutputStream的构造函数会向输出流中写入一个标识头,而ObjectInputStream会首先读入这个标识头.因此,多次以追加方式向一个文件中写入object时,该文件将会包含多个标识头.所以用ObjectInputStream来deserialize这个ObjectOutputStream时,将产生StreamCorruptedException
所以我在试图多加几条记录时就会出现上述的问题,还没有找到解决的办法
1.read out the objects and store them into a container;
and,
2.write them as well as those new ones into a ObjectOutputStream(do not use appending mode). But I don't think this is the best way. GZing.....