繁体   English   中英

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

[英]How do I serialize and deserialize arrayList object?

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

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

[我知道在写入和读取文件之前,我必须对对象进行序列化和反序列化。 我不知道该怎么做。 我在网上搜索,大多数情况下是在main方法中完成的。 但是就我而言,我为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
    }

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM