save changes (permanently) in an arraylist?

2019-03-05 02:45发布

问题:

Is that possible? Like for example, a user added a new item/element into the arraylist (bufferedreader process) and surely, there would be changes happen. My question is that is it possible that even if a user makes changes into the arraylist many times, it would just be permanently there even if they close the program and open it agan, it's s till there.

Note: No usage of .txt

Sorry for asking such question but I am really curious about it. Thank you!

回答1:

When the program stops, all memory it uses is released, including your ArrayList. There's no going around this except not to close the program. If you really need persistent data structures, you will have to write it to the hard drive somehow.

You asked not to use .txt. Well, that's all right, but you will have to create a file somewhere to store this data.

Luckily, ArrayList is serialisable. As long as the elements in it are serialisable, you can easily store it in a file with writeObject, as follows:

try {
    FileOutputStream fos = new FileOutputStream(filename);
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(arraylist);
    oos.close();
} catch(Exception e) {
    e.printStackTrace();
}

And then you can recreate the ArrayList again with readObject.

ArrayList<Data> list;
try {
    FileInputStream fis = new FileInputStream(filename);
    ObjectInputStream ois = new ObjectInputStream(fis);
    list = (ArrayList<Data>) ois.readObject();
    ois.close();
} catch(Exception e) {
    e.printStackTrace();
}

Note that the objects you store in this ArrayList need to be serialisable as well. This means you have to make a writeObject and a readObject method for them if you made these classes.



回答2:

This is possible if your ArrayList is frequently
persisted either on the file system or in a database.
This is what you need to do.



回答3:

The arraylist object you work with is just a variable of your program. While your program keeps a reference to this variable, but once you close the program the variable will disapear. If you want to keep the information inside of the variable you need to use a file or a database, you cannot store a java variable.



回答4:

If I understand you aren't allowed to use a text file to store your data in CSV format, maybe Serialization/Deserialization is what you, or your teacher ;-), want or wants you to do.

Read about ObjectOutputStream and ObjectInputStream and try your best. Here's a little example.