Java 如何序列化和反序列化arrayList对象?
在我的程序中,输入对象存储在arrayList中。问题是我关闭应用程序后会丢失所有数据 这就是为什么我想更进一步,将这些对象存储在磁盘上,以便在关闭应用程序后不会丢失任何数据。最后我想读一下这个文件。我正在学习的课程是:Java 如何序列化和反序列化arrayList对象?,java,serialization,file-io,arraylist,deserialization,Java,Serialization,File Io,Arraylist,Deserialization,在我的程序中,输入对象存储在arrayList中。问题是我关闭应用程序后会丢失所有数据 这就是为什么我想更进一步,将这些对象存储在磁盘上,以便在关闭应用程序后不会丢失任何数据。最后我想读一下这个文件。我正在学习的课程是:ReaderWriter [我知道在编写和读取文件之前,我必须序列化和反序列化对象。我不知道如何做。我在网上搜索过,大多数情况下他们是在main方法中完成的。但在我的情况下,setObject和getObject的类不同,这就是我感到困惑的原因。] 人物信息: public st
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;
}
}
}
读写器:
public class ReaderWriter {
//I want to use this class for serialization and deserialization object
//writing those data into file and reading them
}
使用
ObjectOutputStream
和ObjectInputStream
您PeopleObject
必须实现Serializable
ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream("name"));
stream.writeObject(yourArrayList);
ObjectInputStream stream = new ObjectInputStream(new FileInputStream("name"));
yourArrayList = (List<PeopleObject>)stream.readObject();
ObjectOutputStream=新的ObjectOutputStream(新文件OutputStream(“名称”));
stream.writeObject(您的ArrayList);
ObjectInputStream=新ObjectInputStream(新文件输入流(“名称”);
yourArrayList=(列表)stream.readObject();
See.VGR,我已经看过类似的类型,但可能是我太笨了,不知道如何在我的程序中具体实现它。因为我看到我的主类中有arrayList,对象在不同的类中。我不知道要在哪里序列化和反序列化它。在读取时需要一个小的强制转换:yourArrayList=(ArrayList)stream.readObject();对忘了吧。talex情绪激动地投了一票。但事实是我没有得到那么多,几乎什么都没有。我的arrayList在我的主类中,那么如何在PeopleObject类中实现它呢。我也不知道你的问题是什么,请你重新措辞。我一个字也听不懂。然后冷静下来:)什么是“你的阵列列表”?和“名单”
ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream("name"));
stream.writeObject(yourArrayList);
ObjectInputStream stream = new ObjectInputStream(new FileInputStream("name"));
yourArrayList = (List<PeopleObject>)stream.readObject();