保存一个ArrayList的变化(永久)? [英] save changes (permanently) in an arraylist?

查看:218
本文介绍了保存一个ArrayList的变化(永久)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能吗?像例如,用户增加了一个新的项目/元素插入的ArrayList(的BufferedReader流程),可以肯定,会有变化发生。我的问题是,是否有可能,即使用户更改到ArrayList中很多次,这纯粹是永远存在,即使他们关闭程序并阿甘打开它,它公司的S到那里。

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是serialisable。只要它的元素是serialisable,您可以轻松地将其与的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需要存储的对象是serialisable为好。这意味着你必须做出一个的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.

这篇关于保存一个ArrayList的变化(永久)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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