Please help, I am getting StreamCorruptedException in my application. I am obliged to close the stream for some implementation reasons. Here is a small code similar to the original application The reading of the third Dummy object is causing the Exception. I think it is because I close the stream before writing the third object. What can I do?
class Dummy implements Serializable{
int a;
String b;
public Dummy(int a, String b) {
this.a = a;
this.b = b;
}
void Print(){
System.out.println(a+" "+b);
}
}
public class Tester {
public static void main(String []args){
try {
ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream(new File("test.txt")));
Dummy a=new Dummy (10,"mm.");
Dummy b=new Dummy (20,"nn.");
Dummy c=new Dummy (30,"pp.");
out.writeObject(a);
out.writeObject(b);
out.close();
out=new ObjectOutputStream(new FileOutputStream(new File("test.txt"),true));
out.writeObject(c);
out.close();
ObjectInputStream in=new ObjectInputStream(new FileInputStream(new File("test.txt")));
Vector<Object> v=new Vector<Object>();
v.add(in.readObject());
v.add(in.readObject());
v.add(in.readObject());
((Dummy)v.get(0)).Print();
((Dummy)v.get(1)).Print();
((Dummy)v.get(2)).Print();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}