使用序列化在对象中发送 BufferedImage 的正确方法。写对象读对象
Correct way to send BufferedImage in object with serialization. writeObject readObject
我正在尝试通过套接字发送带有 BufferedImage 的对象。我现在意识到我必须使它成为瞬态的,class 实现可序列化,并覆盖 writeObject 和 readObject 方法。我认为我的写是正确的,但我的阅读我一直给我一个 EOFException。这是我的 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);
}
我认为 readObject 中的 readInt() 正在抛出它。
您的 writeObject 永远不会写入 out。它写入稍后未使用的 ByteArrayOutputStream
更新
参见例如post 图像列表是如何序列化的。您可以跳过计数 writing/reading
这里的问题是您正在阅读尚未编写的内容。如果您希望读取一个 int,则需要 write 一个 int。相反,您将图像转储到输出流的字节数组中,这对序列化的影响为零。
你的代码没有意义。
如果你写一个图像,将它写入对象流,并以相同的方式读回,ImageIO.
注意,如果您遇到异常,肯定有某处的堆栈跟踪。
我正在尝试通过套接字发送带有 BufferedImage 的对象。我现在意识到我必须使它成为瞬态的,class 实现可序列化,并覆盖 writeObject 和 readObject 方法。我认为我的写是正确的,但我的阅读我一直给我一个 EOFException。这是我的 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);
}
我认为 readObject 中的 readInt() 正在抛出它。
您的 writeObject 永远不会写入 out。它写入稍后未使用的 ByteArrayOutputStream
更新 参见例如post 图像列表是如何序列化的。您可以跳过计数 writing/reading
这里的问题是您正在阅读尚未编写的内容。如果您希望读取一个 int,则需要 write 一个 int。相反,您将图像转储到输出流的字节数组中,这对序列化的影响为零。
你的代码没有意义。
如果你写一个图像,将它写入对象流,并以相同的方式读回,ImageIO.
注意,如果您遇到异常,肯定有某处的堆栈跟踪。