I want to write an Object file with append. I have a class NewContact and main class below:
private String name;
private String sex;
private String mail;
private String phone;
private String image;
//setter and getter method. removed it to avoid the long post.
public NewContact() {
}
public NewContact(String name, String sex, String phone, String mail, String image) {
this.name = name;
this.sex = sex;
this.mail = mail;
this.phone = phone;
this.image = image;
}
public String Xuat()
{
return this.getName()+" "+this.getSex()+" "+this.getPhone()+" "+this.getMail()+" "+this.getImage();
}
@Override
public String toString(){
//return this.name+" "+this.sex+" "+this.phone+" "+this.mail+" "+this.image;
return this.getName()+" "+this.getSex()+" "+this.getPhone()+" "+this.getMail()+" "+this.getImage();
}
///main class
public static void main(String[] args) throws IOException, ClassNotFoundException {
File file = new File("F:\\students.txt");
ArrayList<NewContact> students = new ArrayList<NewContact>();
students.add(new NewContact("Tom","Male","99245","f@gmail.com","sdgsg"));
students.add(new NewContact("Mark","Male","365465","wegg@gmail.com","sdgsg"));
students.add(new NewContact("Dave","Male","35346","dfhdfhfdh@gmail.com","sdgsg"));
FileOutputStream fo = new FileOutputStream(file,true);
ObjectOutputStream output = new ObjectOutputStream(fo);
for ( NewContact s : students) {
output.writeObject(s);
//output.reset();
}
output.close();
fo.close();
FileInputStream is = new FileInputStream(file);
ObjectInputStream input = new ObjectInputStream(is);
try {
while(true) {
NewContact s = (NewContact)input.readObject();
System.out.println(s);
}
} catch (EOFException ex) {
}
}
I struggled with this issue for all day yesterday. Couldn't get to work. If I just write normal (no append), it's totally fine. But when I try to append it, it keep getting error StreamCorruptedException: invalid type code: AC.
During the research, I even added this class
public class AppendingObjectOutputStream extends ObjectOutputStream{
public AppendingObjectOutputStream(OutputStream out) throws IOException {
super(out);
}
@Override
protected void writeStreamHeader() throws IOException {
// do not write a header, but reset:
// this line added after another question
// showed a problem with the original
reset();
}
}
STILL not work :(.