gpt4 book ai didi

java - 写入 ObjectOutputStream 附加文件,不断收到 StreamCorruptedException 错误

转载 作者:行者123 更新时间:2023-11-30 10:45:31 25 4
gpt4 key购买 nike

<分区>

我想写一个带有追加的对象文件。我在下面有一个 NewContact 类和主类:

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) {

}
}

我昨天一整天都在为这个问题苦苦挣扎。无法上类。如果我只是写正常(没有追加),那完全没问题。但是当我尝试附加它时,它不断出现错误 StreamCorruptedException: invalid type code: AC。

在研究的过程中,我什至添加了这个类

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();
}
}

还是不行 :(。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com