Ошибка java .io.EOFException - PullRequest
       73

Ошибка java .io.EOFException

0 голосов
/ 30 апреля 2020

Подскажите пожалуйста, как исправить ошибку java .io.EOFException.

 import com.company.Person;

import java.io.*;
import java.time.Period;
import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {

        File file = new File("C:\\Users\\R2D2\\Desktop\\hello.txt");
        File file2 = new File("C:\\Users\\R2D2\\Desktop\\hello2.txt");

        ArrayList<com.company.Person> people = new ArrayList<com.company.Person>();
        people.add(new Person("Alex", 25, 150.5, true));
        people.add(new Person("Bill", 23, 160.5, false));

        try (ObjectOutputStream ous = new ObjectOutputStream(new FileOutputStream(file))) {
            ous.writeObject(people);
            System.out.println("File has been written");

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

        ArrayList<Person> newPeople = new ArrayList<>();

        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file2))) {
            newPeople = ((ArrayList<Person>) ois.readObject());

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

            for (Person p : newPeople)
                System.out.printf("Name: %s \t Age: %d \n", p.getName(), p.getAge());
        }
    }
}

Вылет в следующей строке

   try (ObjectInputStream ois = new ObjectInputStream(new 
   FileInputStream(file2))) {

Пример взят из мануалы, но он не работает ... Пробовал испотльзовать в то время как (ois.available ()> 0), но все равно равно ошибкам.

...