StreamCorruptedException:无效的流头:从文件中读取对象时为79737200

时间:2019-01-02 11:10:57

标签: java objectinputstream objectoutputstream

我创建了一个客户端相似性,其中客户端注册了一个帐户(创建了一个对象),该帐户存储在文件中。

根据需要将对象写入文件,我覆盖了writeStreamHeader()方法。但是当我尝试全部读取它们时,它们的文件将引发异常。

在此处将对象写入文件。

 public static void saveAccaunt(LoginAndPass gamers) {
    boolean b = true;
    FileInputStream fis = null;
    try{
        fis = new FileInputStream("student.ser");
        fis.close();
    }
    catch (FileNotFoundException e)
    {
        b = false;
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        FileOutputStream fileOutputStream = new FileOutputStream("student.ser",true);
        ObjectOutputStream os = null;
        if(b = true){
            os = new AppendingObjectOutputStream(fileOutputStream);
            System.out.println("Объект добавлен!");
        }else {
            os = new ObjectOutputStream(fileOutputStream);
            System.out.println("Создан");
        }
        os.writeObject(gamers);
        os.close();
        fileOutputStream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}


 public static void main(String[] args) {
    try {
        FileInputStream fileInputStream = new FileInputStream("student.ser");
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
        test = new ArrayList<>();
        while (true){
            test.add(objectInputStream.readObject());
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    System.out.println(test.get(0));

}

这是引发异常的错误日志:

  

java.io.StreamCorruptedException:无效的流标头:79737200
  在java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:866)
  在java.io.ObjectInputStream。(ObjectInputStream.java:358)
  在Registratsiya.AllGamers.main(AllGamers.java:48)
  线程“主”中的异常java.lang.NullPointerException   在Registratsiya.AllGamers.main(AllGamers.java:61)

0 个答案:

没有答案