重写writeStreamHeader方法

时间:2018-12-28 06:21:05

标签: java

我制作了一个微型应用程序,在其中创建了一个帐户,每个帐户都是一个存储登录名和密码的对象。我将其添加到文件中,问题在于它不需要一次全部添加到文件中,而是一次按下一次即可添加到文件中:

btnOk.addActionListener(new ActionListener() {
        @Override
        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()));

这是将对象写入文件的代码:

 public static void saveAccaunt(LoginAndPass gamers) {

    try {
        File file = new File("test");
        ObjectOutputStream os1 = new ObjectOutputStream(new FileOutputStream(file));
        os1.writeObject(gamers);
        os1.close();
        ObjectOutputStream os2 = new ObjectOutputStream(new FileOutputStream(file, true)) {
            @Override
            protected void writeStreamHeader() throws IOException {
                reset();
            }
        };
        os2.writeObject(gamers);
        os2.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

但是从文件中读取它们的代码:

 try {
            FileInputStream fileInputStream = new FileInputStream("test");
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
            System.out.println(objectInputStream.readObject());
            System.out.println(objectInputStream.readObject());
            System.out.println(objectInputStream.readObject());

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

问题在于,当我从文件中读取对象时,它就是这样提供的:

    Registratsiya.LoginAndPass@4dd8dc3
Registratsiya.LoginAndPass@6d03e736
java.io.EOFException
    at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2960)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1540)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431)
    at Registratsiya.AllGamers.main(AllGamers.java:37)

为什么不读取第三个对象,毕竟将它们添加了三个,也发生了很多,最多读取两个。

第二天我不能解决问题

1 个答案:

答案 0 :(得分:0)

使用writeObject(gamers)中的第一个os1调用(saveAccaunt()),您将覆盖任何现有的test文件。然后使用第二个(os2)将相同的对象附加到相同的文件中。因此,您基本上最终在test文件中拥有相同对象的两倍。现在,每次调用saveAccaunt()时,都会覆盖现有文件。

这样说,在第二个objectInputStream.readObject()之后,您到达了该文件的末尾,因此在第三次调用时到达了EOFException