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) 
  • It is believed that you need to write objects to the file in one stream. Then they will be read. And if you first write one, then add another, but with a different stream (new ObjectOutputStream), then you get what you get. AC is the type of the title of the new ObjectOutputStream, instead of the class code - Sergey
  • Then what should you do? - WolF Ram
  • Maybe the way stackoverflow.com/questions/15607969/… is here - Sergey
  • Everything seems to work, but knocks out java.io.EOFException - WolF Ram
  • First of all, make sure that you are not trying to read too much from the file. For example, the reading cycle makes an extra iteration. - Sergey

0