save changes (permanently) in an arraylist?

前端 未结 4 1971
北荒
北荒 2021-01-27 06:25

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

4条回答
  •  -上瘾入骨i
    2021-01-27 07:08

    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 list;
    try {
        FileInputStream fis = new FileInputStream(filename);
        ObjectInputStream ois = new ObjectInputStream(fis);
        list = (ArrayList) 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.

提交回复
热议问题