Sometimes, I want to use an ObjectOutputStream
to write something to a file or sending a little image over the network. But BufferedImage
and many other classes don't implement java.io.Serializable
and then the Stream cancels writing. Is there a way avoid that?
Thanks, Martijn
With the FileOutputStream created, we simply pass the instance to the constructor of the ObjectOutputStream. The combination of the FileOutputStream and the ObjectOutputStream will allow Java object serialization to happen at the file level.
You don't always require serialization/deserialization. If you're sending an object over a network, then it gets serialized to send it via a byte stream. That's the point of serialization, precisely so that you CAN send via a network.
You can prevent member variables from being serialized by marking them with the NonSerialized attribute as follows. If possible, make an object that could contain security-sensitive data nonserializable. If the object must be serialized, apply the NonSerialized attribute to specific fields that store sensitive data.
If you want a class object to be serializable, all you need to do it implement the java. io. Serializable interface. Serializable in java is a marker interface and has no fields or methods to implement.
Only objects that support the java.io.Serializable interface can be written to streams.
-- ObjectOutputSteam docs
However, you could avoid all this by using one of the classes in javax.imageio
. Specifically the ImageIO.write(RenderedImage, String, OutputStream)
method, because BufferedImage
implements RenderedImage
. You can then read it back out with ImageIO.read(InputStream)
, which returns a BufferedImage
.
You'll probably want a different OutputSteam
type, though. In addition to the normal OutputStream
s, there are several special ImageOutputStream
s.
Edit: I missed this before:
To get a list of valid strings for the middle argument, you can call ImageIO.getWriterFormatNames()
No. That's like saying, "I want to display an object as text, but don't know anything about how to convert it into a string."
The entire purpose of Serializable
is to say "I know how to be serialized to a stream!" - if we didn't need it, we wouldn't have it.
Now if you have an object which implements Serializable
but contains something which itself doesn't implement Serializable
, but which you could work out some way of serializing by hand, you could always customize the serialization of the container object yourself.
Basically ObjectOutputStream
is designed for Java's serialization framework. If you don't want to use the serialization framework, don't use ObjectOutputStream
. Images in particular are likely to have their own "native format" which ImageIO
can deal with (as R. Bemrose noted).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With