I create a small application, when you click on the registration button, an object is created.
public void actionPerformed(ActionEvent e) { if(tfLogin.getText().length()>=0 && tfPassword.getText().length()>=0 && tfPasswordTwo.getText().equals(tfPassword.getText())){ AllGamers.saveAccaunt(new LoginAndPass(tfLogin.getText(), tfPassword.getText())); } Then the object is saved to the file:
public static void saveAccaunt(LoginAndPass gamers){ try { FileOutputStream fileOutputStream = new FileOutputStream("SaveAc",true); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); objectOutputStream.writeObject(gamers); } catch (IOException e) { e.printStackTrace(); } } Everything works fine here, when I read the file, everything is fine too:
try { FileInputStream fileInputStream = new FileInputStream("SaveAc"); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); Object o = objectInputStream.readObject(); LoginAndPass l1 = (LoginAndPass) o; System.out.println(l1.getLogin()); System.out.println(l1.getPassword()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } The problem is that when I want to add another account to the file, that is, another object, like it adds it, but when I try to read them, it gives an error:
try { FileInputStream fileInputStream = new FileInputStream("SaveAc"); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); Object o = objectInputStream.readObject(); LoginAndPass l1 = (LoginAndPass) o; System.out.println(l1.getLogin()); System.out.println(l1.getPassword()); Object o1 = objectInputStream.readObject(); LoginAndPass l2 = (LoginAndPass) o1; System.out.println(l2.getLogin()); System.out.println(l2.getPassword()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } Here is the error code:
java.io.StreamCorruptedException: invalid type code: AC at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1601) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431) at Registratsiya.AllGamers.main(AllGamers.java:32)