De-serialize a file and return an arraylist containing the objects in the file

喜夏-厌秋 提交于 2019-12-25 02:09:13

问题


I have serialized an arraylist to a file, but have difficulties deserializing them back into an arraylist and print them. How can I edit my code? Thanks!

This is the serializing method:

    public static void writeMembersToDisk(ArrayList<Member> membersList) {
    ObjectOutputStream out = null;
    try {
        out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("members.s")));

        for(Member cmd : membersList) {
            out.writeObject(cmd);
        }
    } catch (Exception e) {
        System.err.println("Error: " + e.toString());
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            System.err.println("Error: " + e.toString());
        }
    }
}

I don't know how to deserialize the file back to the an arraylist, this is my code:

    public static ArrayList<Member> readMembersFromDisk() {

        ArrayList<Member> cmd = null;

        try {
            FileInputStream is = new FileInputStream("members.s");

            ObjectInputStream os = new ObjectInputStream(is);                           

            cmd = (ArrayList) os.readObject();

            os.close();  

        } catch (Exception e) {
            System.err.println("Error: " + e.toString());            
        }

        return cmd;

}

When I try to print the arraylist, I get an error: "java.lang.ClassCastException: Member cannot be cast to java.util.ArrayList"

    public static void main(String[] args) {
    ArrayList<Member> list = MembersListFileManager.readMembersFromDisk();      
            System.out.println(list);
}

回答1:


You are writing one Member object at a time from the original list.

for(Member cmd : membersList) {
    out.writeObject(cmd);
}

But while reading you're trying to cast a Member object into an ArrayList which is wrong.

You need to cast the read object to Member by doing something like this:

Member member = (Member) os.readObject();

But this will just fetch the first object serialized. To get all the objects, loop through and keep adding each member object read into the arraylist.

// Pseudo-code
loop till objects are there{
    Member member = (Member) os.readObject(); // read the object
    cmd.add(member); // add it to the list
}

One of the ways to loop through it is,

while (true) {
    try {
        Member member = (Member) os.readObject();
        // Do something with the object
    } catch (EOFException e) {
        break; // Break when the end-of-file is reached
    }
}
os.close();


来源:https://stackoverflow.com/questions/21520337/de-serialize-a-file-and-return-an-arraylist-containing-the-objects-in-the-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!