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

时间:2015-04-21 15:18:07

标签: java serialization file-io arraylist deserialization

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

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

[我已经知道在写入和读取文件之前,我必须序列化和反序列化对象。我不知道该怎么做。我在网上搜索过,大多是他们在主要方法中完成的。但在我的情况下,我有不同的setObject和getObject类,这就是为什么我感到困惑。]

PeopleInfo:

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;
        }

    }

}

PeopleObject:

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
    }

1 个答案:

答案 0 :(得分:3)

使用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();