gpt4 book ai didi

java - 如何序列化和反序列化 arrayList 对象?

转载 作者:行者123 更新时间:2023-11-30 08:13:55 25 4
gpt4 key购买 nike

在我的程序中,输入对象存储在 arrayList 中。问题是我在关闭应用程序后丢失了所有数据。

这就是为什么我想更进一步将这些对象存储在磁盘上,以便在关闭应用程序后不会丢失任何数据。最终我想阅读文件。我正在处理的类是:ReaderWriter

[我开始知道在写入和读取文件之前,我必须序列化和反序列化对象。我不知道该怎么做。我在网上搜索过,大部分都是在 main 方法中完成的。但在我的例子中,我有不同的 setObject 和 getObject 类,这就是我感到困惑的原因。]

人员信息:

public static void main(String[] args) {
System.out.println("WELCOME TO MY PERSONAL DATABASE\n\n");
Scanner input = new Scanner(System.in);
List<PeopleObject> peopleObject = new ArrayList<PeopleObject>();
String name;
int age;
int option;

while (true) {

System.out.println("1. Enter info\n"
+ "2. Print them out\n"
+ "3. Exit\n"
+ "*********"
+ "*********\n");
option = input.nextInt();
input.nextLine();

switch (option) {
case 1:
PeopleObject p_object = new PeopleObject();
System.out.println("Enter your friends name:");
p_object.setName(input.nextLine());
System.out.println("Enter age: ");
p_object.setAge(input.nextInt());

peopleObject.add(p_object);
System.out.println("\n");
break;
case 2:
System.out.println("Name \tage");
for (PeopleObject printPeopleObject : peopleObject) {
System.out.println(printPeopleObject);

}
System.out.println("\n\n");
break;
case 3:
return;
}

}

}

人物对象:

private String name;
private int age;

public PeopleObject() {
this.name = null;
this.age = 0;

}

public void setName(String name) {
this.name = name;
}

public void setAge(int age) {
this.age = age;

}

@Override
public String toString() {
return name + "\t\t" + age;
}

读写器:

public class ReaderWriter {
//I want to use this class for serialization and deserialization object
//writing those data into file and reading them
}

最佳答案

使用ObjectOutputStreamObjectInputStream

PeopleObject 必须实现Serializable

ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream("name"));
stream.writeObject(yourArrayList);

ObjectInputStream stream = new ObjectInputStream(new FileInputStream("name"));
yourArrayList = (List<PeopleObject>)stream.readObject();

关于java - 如何序列化和反序列化 arrayList 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29776394/

25 4 0