Writing an ArrayList of non-string objects to file

假装没事ソ 提交于 2020-01-07 02:15:50

问题


EDIT: I solved the problem, I forgot to close the ObjectOutputStream. 'doh! I'll leave the question just in case someone wants to propose a more elegant option, which would be much appreciated.

I currently am trying to write a class called phonebook to file, which contains an ArrayList of objects called PhonebookEntry. Here is the Phonebook class:

import java.util.ArrayList;
import java.io.*;

public class Phonebook implements Serializable
    private static final long serialVersionUID = 1;

    ArrayList<PhonebookEntry> phonebookEntries = new ArrayList<PhonebookEntry>();

    public void addEntry(String name, String number) {
        PhonebookEntry newEntry = new PhonebookEntry(name, number);
        phonebookEntries.add(newEntry);
    }

}

I have tried using a simple ObjectInput/OutputStream and I can get it to save that way, but not to load (usually with an EOFExcpetion). Is there an elegant way to save an object like this, or is there any way to save an ArrayList of objects to a file?


回答1:


The following works. I'm guessing you're missing flush() or close().

public static void main(final String[] args) throws IOException, ClassNotFoundException {
    final ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("test.out"));
    final Phonebook phonebook = new Phonebook();
    out.writeObject(phonebook);
    out.flush();
    out.close();

    final ObjectInputStream in = new ObjectInputStream(new FileInputStream("test.out"));
    final Object o = in.readObject();
    System.out.println(o);
}



回答2:


When you want your PhonebookEntries to be serialized the standard way, its members must be serializable itself.




回答3:


A couple of different issues, the code as written, which I'm assuming is a sample code (so I'm not going to fix it) is never going to fill in anything since you keep releasing the object. So you would end up with null,null for each add.

To answer your question, not sure how much more eligent it is but the shorter version is:

for (PhonebookEntry pbe : phonebookEntries) {
    System.out.println("Name: " + pbe.getName());
    ....
}


来源:https://stackoverflow.com/questions/8417051/writing-an-arraylist-of-non-string-objects-to-file

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