0

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?

Elianora
  • 194
  • 1
  • 13

3 Answers3

0

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);
}
Reverend Gonzo
  • 39,701
  • 6
  • 59
  • 77
0

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

DerMike
  • 15,594
  • 13
  • 50
  • 63
-1

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());
    ....
}
awm
  • 2,723
  • 2
  • 18
  • 26
  • I'm not sure I understand awm's answer... it has nothing to do with file io, but maybe I'm missing something... I'm trying to save the entire Phonebook object into a file with all of the PhonebookEntry objects inside it. – Elianora Dec 07 '11 at 15:05