save changes (permanently) in an arraylist?(将更改(永久)保存在数组列表中?)
问题描述
这可能吗?例如,用户将新项目/元素添加到数组列表(缓冲读取器进程)中,肯定会发生变化.我的问题是,即使用户对数组列表进行了多次更改,是否有可能即使他们关闭程序并再次打开它,它也会永久存在,直到那里.
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.
这篇关于将更改(永久)保存在数组列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将更改(永久)保存在数组列表中?
基础教程推荐
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 大摇大摆的枚举 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 从 python 访问 JVM 2022-01-01
