Saving a Serializable Object to a File with Some Excluded Data

I have an object that allows me to store a BufferedImage in my object file. In the same object, I have a BufferedImage variable that I use to cache the image after loading it for the first time from an array of raw data. Everything works fine when I create an object and save it to a file since BufferedImage is null. The problem occurs when I update the loaded object, and the variable is initialized, and I want to save the object after updating it.

Is it possible to save the serializable object to a file, excluding some variables? Or maybe I can reset somehow change the BufferedImage variable while saving the file?

Thanks in advance, Serhiy.

+6
java serialization file-io bufferedimage
source share
2 answers

you should mark the attribute that you do not want to serialize as transient:

private transient BufferedImage image; 
+15
source share

Variables can be marked as transient . If a variable is marked as transient, it will not be serialized when your object is serialized.

Also, when you retrieve an object from a saved state, the transient variable will have a null value. Therefore, you need to make sure that you reinitialize the transition variable before using it.

+4
source share

All Articles