首页 > 解决方案 > StreamCorruptedException:无效的流标头:从文件中读取对象时出现 79737200

问题描述

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

对象根据需要写入文件,我重写了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
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:866)
at java.io.ObjectInputStream.(ObjectInputStream.java:358)
at Registratsiya.AllGamers.main(AllGamers.java :48)
Registratsiya.AllGamers.main(AllGamers.java:61) 的线程“main”java.lang.NullPointerException 中的异常

标签: javaobjectinputstreamobjectoutputstream

解决方案


推荐阅读