Home > Blockchain >  Filling in List if found for deserialization is not found
Filling in List if found for deserialization is not found

Time:10-29

I have a javafx application with a Controller which has a List of Book objects. I've managed to serialize this list when I want, and deserialize it when my application closes or updates the List. However, I would like to make it so that if the file is not found (aka, the first time the application is run), the List would instead be filled with predetermined objects. How may I achieve this?

Here's the method I use to deserialize:

public  void DeserializeDatabase() throws FileNotFoundException { //the name database is just required for the exercise
        try (ObjectInputStream ois = new ObjectInputStream(
                new FileInputStream("members.dat"))) {
            while (true) {
                try {
                    User user = (User)ois.readObject();
                    users.add(user);
                } catch (EOFException eofe){
                    break;
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(e);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

Here's the constructor for the Controller:

 public Database() throws FileNotFoundException {
        this.users = new ArrayList<>();
        //users.add(new User(1, "user1", "lastName1", LocalDate.of(2020, 4, 29), "0000"));
        //users.add(new User(2, "user2", "lastName2", LocalDate.of(1992, 4, 17), "0000"));
        DeserializeDatabase();
    }

(the commented out objects are the ones I would like to add if the file is not found)

Any help is greatly appreciated, please do tell if more information is required

CodePudding user response:

User @CryptoFool was right. I ended up catching the FileNotFoundException and added the default objects there. The method ended up as:

public  void DeserializeDatabase() {
    try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("members.dat"))) {
        while (true) {
            try {
                User user = (User) ois.readObject();
                users.add(user);
            } catch (EOFException eofe) {
                break;
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        }
    } catch (IOException fnf) {
        users.add(new User(//user stuff);
        users.add(new User(//user stuff);
    }
}
  • Related