Reputation: 97
I'm trying to send an object with a BufferedImage through a socket. I now realize that I have to make that it transient, the class implement serializable, and override the writeObject and readObject methods. I think my write is correct but my read I keeps giving my an EOFException. Here is my class:
private void writeObject(ObjectOutputStream out)throws IOException{
out.defaultWriteObject();
//write buff with imageIO to out
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", baos);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException{
in.defaultReadObject();
//read buff with imageIO from in
DataInputStream dis = new DataInputStream(in);
int len = dis.readInt();
byte[] data = new byte[len];
dis.readFully(data);
dis.close();
in.close();
InputStream ian = new ByteArrayInputStream(data);
image= ImageIO.read(ian);
}
I think readInt() in readObject is throwing it.
Upvotes: 1
Views: 915
Reputation: 310850
The problem here is that you are reading things that haven't been written. If you expect to read an int, you need to write an int. Instead you are dumping the image to a byte array out out stream, which has zero effect on the serialization whatsoever.
Your code doesn't make sense.
If you write an image, write it to the object stream, and read it back the same way, with ImageIO.
NB If you are getting an exception there is certainly a stack trace somewhere.
Upvotes: 0
Reputation: 57381
Your writeObject never writes to out. It writes to the ByteArrayOutputStream which is not used later
UPDATE See e.g. the post how list of images is serialized. You can skip the count writing/reading
Upvotes: 1