[英]Write to disk an object that contains a BufferedImage
I have an object BatchStat
e that has pointers to a number of pieces of data, including a BufferedImage
. 我有一个对象
BatchStat
e,该对象具有指向许多数据的指针,包括BufferedImage
。 I need to serialize the object. 我需要序列化对象。
Here's a simplified version of my BufferedImage
: 这是我
BufferedImage
的简化版本:
public class BatchState implements Serializable{
private int anInt;
//A bunch of other primitives and objects
//...
private transient Image image; //This is the BufferedImage
//Constructors, methods, and so forth
//...
}
I have made the Image transient so that I can then write it to a different file using ImageIO. 我已将Image设置为瞬态,以便随后可以使用ImageIO将其写入另一个文件。
I am trying to serialize the object using this code: 我正在尝试使用以下代码序列化对象:
public void saveState(){
ObjectOutputStream oos = null;
FileOutputStream fout = null;
try{
fout = new FileOutputStream("data/saved/"+Client.getUser()+".sav", true);
oos = new ObjectOutputStream(fout);
oos.writeObject(batchState);
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
However, any time I call this method, my program throws the follow exception: 但是,无论何时调用此方法,我的程序都会引发以下异常:
java.io.NotSerializableException: java.awt.image.BufferedImage
This in spite of the fact that the BufferedImage is transient. 尽管BufferedImage是瞬态的,但这仍然可行。
I am looking for one of two solutions: 我正在寻找以下两种解决方案之一:
BufferedImage
along with the rest of the data, or BufferedImage
和其余数据,或者 BatchState
to one file and then write the BufferedImage
to a separate file. BatchState
序列化为一个文件,然后将BufferedImage
写入一个单独的文件。 Either solution is fine. 两种解决方案都可以。
您可以编写一个自定义的writeObject()
方法,该方法首先调用out.defaultWriteObject()
,然后调用ImageIO.write(image, "jpeg", out)
(或您喜欢的任何格式ImageIO.write(image, "jpeg", out)
,以及一个类似的自定义readObject()
方法,该方法执行以下操作:有关这些方法的正确签名,请参见对象序列化规范。
Solved. 解决了。 It involved some other data that I didn't include in the code that I showed above.
它包含了我上面显示的代码中未包含的其他一些数据。 Your guys' comments helped me realize what the problem was, though.
你们的评论帮助我意识到了问题所在。
It turns out that the BufferedImage there visible wasn't the problem at all. 事实证明,那里可见的BufferedImage根本不是问题。 I had a pointer to another object which ALSO contained a BufferedImage, and it was that other BufferedImage (nested in another object) that was causing the OutputStream to throw its exception.
我有一个指向另一个对象的指针,该对象还包含一个BufferedImage,并且是另一个BufferedImage(嵌套在另一个对象中)导致OutputStream抛出异常。
Moral of the story: ObjectOutputStream will serialize even deeply nested objects. 故事的寓意:ObjectOutputStream甚至可以序列化深度嵌套的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.