tmaxxcar
tmaxxcar

Reputation: 309

Saving information using Serializable

I am attempting to get my program to save the data inputted by a user. Currently, I am getting a:

java.io.NotSerializableException: java.awt.image.BufferedImage error

Now, what I have done is implement the FileWriter in my user interface class, and by examining the text file it appears it is trying to save all of the information about the text boxes and labels that I have implemented on my UI. In my main class that my UI is based off of, there is an ArrayList which holds the objects of my project. I need to serialize these objects but they contain a BufferedImage. I think I have found a way to work around the BufferedImage error, but I do not want the entire UI to be serialized.

So my question is, should I move the serialization method into the class that contains my ArrayList of objects, so that the UI will not be serialized?

Upvotes: 2

Views: 1068

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

Mark BufferedImage fields with transient keyword which indicates that a field should not be serialized.

class A {
    transient BufferedImage bufferedImage;
    ...

then you can customize serialization by implementing the following methods in class A

private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException{
    s.defaultWriteObject();
    // extract bytes from bufferedImage and write them
    ...

private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
    s.defaultReadObject();
    // read bytes and re-create bufferedImage
    ...

Upvotes: 3

Andrew Thompson
Andrew Thompson

Reputation: 168825

..should I move the serialization method .. so that the UI will not be serialized?

Yes. Only the things that specifically need serializing, should be serialized.

Upvotes: 1

Related Questions