StreamCorruptedException: неверный заголовок потока: 79737200 при чтении объектов из файла - PullRequest
0 голосов
/ 02 января 2019

Я создаю сходство клиентов, когда клиенты регистрируют учетную запись (объект создается), которая хранится в файле.

Объекты записываются в файл по мере необходимости, я переопределяю метод 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)в Регистрации.AllGamers.main (AllGamers.java:48)Исключение в потоке "main" java.lang.NullPointerException в Registratsiya.AllGamers.main (AllGamers.java:61)

...