从文件中读对象时抛出的异常:java.io.StreamCorruptedException: unexpected block data
如题:
这是书上的一个例子:
//写对象到文件中。
private void saveSketch(File outFile) {
try {
ObjectOutputStream out = new ObjectOutputStream(
new BufferedOutputStream(
new FileOutputStream(outFile)));
out.writeObject(m_model); // Write the sketch to the
// stream
out.close(); // Flush & close it
} catch(IOException e) {
System.err.println(e);
}
}
读对象到文件中:
public void insertModel(String filePath){
File inFile = new File(filePath);
try {
ObjectInputStream in = new ObjectInputStream(
new BufferedInputStream(
new FileInputStream(inFile)));
m_model = (SketchModel)in.readObject();
in.close();
} catch(Exception e) {
System.out.println(e);
}
}
就这样两段程序,我用书上的工程编译后,执行正常,可以将对象保存在文件中并读出来。把这段代码拷到我自己的工程中,也可以用。
问题在于:书上的工程产生的文件,用我自己的工程无法读出对象:报java.io.StreamCorruptedException: unexpected block data。
而用我自己的工程创建的对象,用书上的工程读不出来,报:
java.lang.ClassNotFoundException
不知是何原因。