2

I'm working on a program about students (saving the name, age and other information into objects and storing those objects into an arrayList). So far so good, I even got the JFrames to work exactly how I want them but the problem shows up when I try to write all that information in a text file.

How can I do that?

I tried the FileOutputStream with the ObjectOutputStream but I'm most likely not doing it right since I keep getting an IOException.

An example of a program storing an arrayList with 2 or more Objects containing 2 or more variables each is pretty much what I'm looking for.

As for the loading of that saved array, I think I can figure it out but an explaination on that would still be apreciated.

I've seen a couple of times on different websites people suggesting to do (but it gives me an IOException)

    FileOutputStream fos=new FileOutputStream("FileName.txt");
    ObjectOutputStream oos=new ObjectOutputStream(fos);

    oos.writeObject(myObjectArrayList);
4
  • 1
    What IOException are you getting? Commented Aug 31, 2013 at 14:29
  • 1
    Although it makes no technical difference, it would be better practice to use a different file extension, such as .dat or .ser. It simply helps define the contents of a file. Commented Aug 31, 2013 at 14:29
  • 1
    @BlackBox s/format/extension/. The format of the file doesn't really change. Commented Aug 31, 2013 at 14:30
  • @ChrisJester-Young Thanks, was a bad choice of words. Commented Aug 31, 2013 at 14:33

2 Answers 2

3

By default ArrayList is Serializable.

But the Objects inside the list also must implement Serializable interface.

While writing make sure that your Student class implemented the java.io.Serializable

Sign up to request clarification or add additional context in comments.

Comments

0

While serializing your ArrayList to a file you need to make sure the object that list contains are also serializable. So make sure your Student class implements Serializable interface.

1 Comment

It clearly states that I'm supposed to avoid this sort of thing but... Thanks a lot I've been stuck on this all day.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.