objectoutputstream 读取错误

2025-04-27 22:39:34
推荐回答(1个)
回答1:

不知道楼主找到原因没有,不过我还是说一下给以后碰到此问题的孩子也看看吧。原因可能如下:1、你的Film类没有实现Serializable接口,所以导致导致了这样的问题(不过犯这种错的可能性似乎不是很大)

2、你的Film是一个内部类,比如你的外部类是Test,File类写在它里面。如果这是Film实现了Serializable接口,但Test没有实现的话,同样也会报错的,因为每个内部类中有一个隐含的引用指向外部类,如果外部类没有实现Serializable接口,内部类也还是不能序列化的。以下是代码,测试通过:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.*;
import java.util.*;

@SuppressWarnings("serial")
public class Test implements Serializable {
public static void main(String[] args) throws FileNotFoundException, ClassNotFoundException, IOException {
new Test().test();
}

@SuppressWarnings("unchecked")
private void test() throws FileNotFoundException, IOException, ClassNotFoundException {
Map map = new HashMap();
map.put(1, new Film("变形金刚", 2));
map.put(2, new Film("钢铁侠", 2));
map.put(3, new Film("复仇者联盟", 2));

ObjectOutputStream oos = null;
oos = new ObjectOutputStream(new FileOutputStream("D:\\map.txt", false));
oos.writeObject(map);
oos.close();


ObjectInputStream ois = null;
ois = new ObjectInputStream(new FileInputStream("D:\\map.txt"));
Map m = new HashMap();
m = (Map) ois.readObject();
ois.close();
System.out.println(m.toString());
}

class Film implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int duration;

public Film(String name, int duration) {
this.name = name;
this.duration = duration;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
}
}