-2

I am making a simple application in Java (Animal shelter), it allows you to add animals to the list, edit free places, send email when the free space ends and all the changes are saved when the program closes and loaded after it is turned on.

However, the list of animals (ArrayList) is saved in one file, a list of free places in the second, email address (string) in the third, etc. ...
I have tried to place objects that need to be saved in one collection (ArrayList ), but this file does not load correctly.

Any ideas how to save and read different types in a txt file?

Example of my import/export class:

 void autoSave() {

    try {
        FileOutputStream fout = new FileOutputStream(path);
        ObjectOutputStream oos = new ObjectOutputStream(fout);
        oos.writeObject(AddAnimalScene.listOfAnimals);
        oos.close();

        FileOutputStream fout1 = new FileOutputStream(path1);
        ObjectOutputStream oos1 = new ObjectOutputStream(fout1);
        oos1.writeObject(EditFreeSpaceScene.places);
        oos1.close();

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


void autoLoad() {
    try {
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(path));
        ArrayList<Animal> LoadedAnimalList = (ArrayList<Animal>) in.readObject();
        in.close();
        AddAnimalScene.listOfAnimals = LoadedAnimalList;

        ObjectInputStream in1 = new ObjectInputStream(new FileInputStream(path1));
        Integer LoadedPlaces = (Integer) in1.readObject();
        in1.close();
        EditFreeSpaceScene.places = LoadedPlaces;

    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
    }
}
Dimitar
  • 4,402
  • 4
  • 31
  • 47

1 Answers1

0

A tip: Always read the Javadoc, especially as a beginner. Might be challenging at first, but it will pay off later. In my opinion, consulting the official documentation is always the right way to clear any issues.

From the ObjectOutputStream Javadoc:

Only objects that support the java.io.Serializable interface can be written to streams.

Your Animal class should implement Serializable interface.

On the other hand, if you want to explicitly specify a field should not be serialized, you could use the transient modifier.

Dimitar
  • 4,402
  • 4
  • 31
  • 47