我无法从文件中读取其他对象:java.io.streamcorruptedexception:无效类型代码:ac

问题描述

我试图从文件中读取所有保存的对象,但我只能读取第一个,然后出现异常 (java.io.streamcorruptedexception: invalid type code: ac)

这是我的代码

public void loadfile()
{
try{
FileInputStream file = new FileInputStream("accounts.dat");
ObjectInputStream inputfile = new ObjectInputStream(file);
boolean endoffile=false;
while(!endoffile){
try{
   
accounts2.add((Account) inputfile.readobject());
}catch(EOFException e){
endoffile=true;
}
catch(Exception f){
JOptionPane.showMessageDialog(null,f.getMessage());
}
}
inputfile.close();
   
}catch(IOException e){
JOptionPane.showMessageDialog(null,e.getMessage());
}

}
public void savefile(){
try{
FileOutputStream file = new FileOutputStream("accounts.dat",true);
ObjectOutputStream outputfile = new ObjectOutputStream(file);
for (int i =0 ; i < accounts.size();i++)
{


outputfile.writeObject(accounts.get(i));
}
    outputfile.close();
 JOptionPane.showMessageDialog(null,"Succesfully Registered");
 this.dispose();
    
    
    
}catch(IOException e){
JOptionPane.showMessageDialog(null,e.getMessage());
}
}

解决方法

如果您尝试将 inputfile.readObject() 值放入一个变量中,那么您会在每次迭代中为其赋予一个新值吗?

,

我认为这是因为有 2 个 ObjectOutputStream,并且(我不确定),有时第一个没有/坏关闭...也许尝试使用相同的 OOS?