【发布时间】:2013-12-11 06:08:22
【问题描述】:
我有一个对象BatchState,它有指向多条数据的指针,包括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
//...
}
我已将 Image 设为瞬态,以便我可以使用 ImageIO 将其写入不同的文件。
我正在尝试使用此代码序列化对象:
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();
}
}
但是,每当我调用此方法时,我的程序都会抛出以下异常:
java.io.NotSerializableException: java.awt.image.BufferedImage
尽管 BufferedImage 是瞬态的。
我正在寻找两种解决方案之一:
- 找到一种方法将
BufferedImage与其余数据一起序列化,或者 - 想办法将
BatchState序列化到一个文件中,然后将BufferedImage写入一个单独的文件中。
任何一种解决方案都可以。
【问题讨论】:
-
您的代码对我来说运行良好(当然是初始化图像并更改文件名)。您确定没有忘记标记为瞬态的另一个 Image 变量吗?
-
您的代码不会引发该异常。您必须在
image.上运行没有transient关键字的旧版本 -
如需尽快获得更好的帮助,请发帖 SSCCE。顺便说一句 - 存储一堆不同信息的好方法是在 Zip 文件中。每个资源在 Zip 中都可以有自己的“路径”,而且它们很容易访问。
标签: java serialization bufferedimage transient