简体   繁体   中英

I can't read the other objects from file: java.io.streamcorruptedexception: invalid type code: ac

I am trying to read all the saved objects from the file, but I am only able to read the first one and then an exception appears ( java.io.streamcorruptedexception: invalid type code: ac )

Here is My Code:

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

If you try to put the inputfile.readObject() value into a variable then you giving a new value to it in every iteration?

I think that's because there are 2 ObjectOutputStream, and (I'm not sure about this), it's possible that sometimes the first one is not/bad closed... Maybe try to use the same OOS?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM