Ich möchte eine Objektdatei mit Anhängen schreiben. Ich habe eine Klasse NewContact und Hauptklasse unter:Schreiben ObjectOutputStream Datei anhängen, erhalten StreamCorruptedException Fehler
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","[email protected]","sdgsg"));
students.add(new NewContact("Mark","Male","365465","[email protected]","sdgsg"));
students.add(new NewContact("Dave","Male","35346","[email protected]","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) {
}
}
ich gestern mit diesem Thema für den ganzen Tag zu kämpfen. Ich konnte nicht zur Arbeit kommen. Wenn ich nur normal schreibe (kein Append), ist das völlig in Ordnung. Aber wenn ich versuche, es anzuhängen, erhält es Fehler StreamCorruptedException: ungültiger Typencode: AC.
Während die Forschung, habe ich auch diese Klasse
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();
}
}
immer noch nicht :(.
Speziell wird der Header geschrieben, wenn der Stream geöffnet wird (für die Ausgabe). –
Ich habe das schon einmal versucht, aber nicht funktioniert :( –
@StephenC eigentlich tat ich das vorher. sogar versucht, "reset();" in der WriteStreamHeader-Methode, aber es hilft nicht :(. –