java对象的序列化

来源:百度知道 编辑:UC知道 时间:2024/09/21 08:42:11
public class Files {
public static void main(String s[]) {
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
BufferedImage screenshot = null;
try {
screenshot = (new Robot()).createScreenCapture(new Rectangle(0, 0,
(int) d.getWidth(), (int) d.getHeight()));
} catch (Exception ex) {
System.out.println(ex);
}

Myimg img = new Myimg(screenshot);
FileOutputStream fos=null;
try{
fos = new FileOutputStream("D:\\t.tmp");
}catch(FileNotFoundException e){

}
ObjectOutputStream oos=null;
try{
oos = new ObjectOutputStream(fos);
}catch(IOException e){

}
try{
oos.writeObject(img);
System.out.println("success");
}catch(NotSerializableException e){
System.out.println("error");

基本同意楼上的
不过补充一下,BufferedImage是jdk中的类,不是楼主想序列化就能序列化的。所以问题就在这儿了,因为BufferedImage本身没有实现Serializable,所以是不能将其写入的,也就是在写入Myimg 的时候无法完成BufferedImage对象的序列化

你的异常是什么???
看你的代码,我觉得你序列化的类有点问题,你应该序列化的类是你最后写入的那个类,Myimg只是将BufferedImage封装了,并不是写入了这个类,如果你最后写入的是BufferedImage的话,建议你序列化BufferedImage试试。

如果BufferedImage类是API中的类的话,那你可以写个一个类继承BufferedImage,系列化这个类。