[英]Best approach to save permanently an ArrayList of a personalised type
I have an ArrayList of Persons (ArrayList<Person>)
, I want to store that ArrayList in a persistent data type. 我有一个ArrayList的人
(ArrayList<Person>)
,我想将该ArrayList存储在持久数据类型中。 SharedPreferences are a solution BUT it's just manipulating String, int, float`... variables. SharedPreferences是一个解决方案,但它只是操作String,int,float ......变量。 Do you have some ideas?
你有什么主意吗? Thank you very much.
非常感谢你。
I'd store each Person
in the array as a row in an SQLite database. 我将每个
Person
存储在数组中作为SQLite数据库中的一行。 When you want to read it back into the program, each row becomes a Person
object in the array. 当您想将其读回程序时,每一行都将成为数组中的
Person
对象。
Much simpler is to use java Serialisation
. 使用Java
Serialisation
要简单得多。
You just need an Persons class: 您只需要一个Persons类:
public class Persons {
ArrayList<Person> personList;
}
Then simply use 然后简单地使用
// init Persons
Persons person = new Persons();
// add some
persons.personList.add(new Person());
// write out
ObjectOutpuStream oos = new ObjectOutputStream(new BufferOutputStream(new FileOutputStream("personsDB.ser")));
oos.writeObject(persons);
oos.close();
read back with 读回
ObjectInputStream ois = new ObjectInputStream(new BufferedInpuStream(new FileInpuStream("personsDB.ser")));
persons = (Persons) ois.readObject();
ois.close();
// ready! Java does that all for you; since Persons is one object which contains something
The disadvantage is when battery power is lost during writing. 缺点是在写入过程中电池电量耗尽。 Some people write to a temporary file first, delete the old and rename to the correct file name.
有人先写一个临时文件,删除旧文件,然后重命名为正确的文件名。
For high performance (much less space, much faster) You could use DataOutputStream
, but then you have to write all fields yourself (but this is simple too) 为了获得高性能(更少的空间,更快的速度),您可以使用
DataOutputStream
,但是随后您必须自己编写所有字段(但这也很简单)
您必须使用数据库或将json响应写入文件并从文件中读取它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.