将更改(永久)保存在数组列表中? [英] save changes (permanently) in an arraylist?

查看:46
本文介绍了将更改(永久)保存在数组列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能吗?例如,用户将新项目/元素添加到数组列表(缓冲读取器进程)中,肯定会发生变化.我的问题是,即使用户对数组列表进行了多次更改,是否有可能即使他们关闭程序并再次打开它,它也会永久存在,直到那里.

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.

注意:不使用 .txt

Note: No usage of .txt

很抱歉提出这样的问题,但我真的很好奇.谢谢!

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

推荐答案

当程序停止时,它使用的所有内存都会被释放,包括你的 ArrayList.除了不关闭程序外,没有其他办法.如果你真的需要持久化数据结构,你将不得不以某种方式将它写入硬盘.

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.

您要求不使用 .txt.好吧,没关系,但是您必须在某个地方创建一个文件来存储这些数据.

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

幸运的是,ArrayList 是可序列化的.只要里面的元素是可序列化的,就可以很方便的用writeObject把它存到一个文件中,如下:

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();
}

然后您可以使用 readObject 重新创建 ArrayList.

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();
}

请注意,您存储在此 ArrayList 中的对象也需要是可序列化的.这意味着如果你创建了这些类,你必须为它们创建一个 writeObject 和一个 readObject 方法.

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.

这篇关于将更改(永久)保存在数组列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆