我还有另一个序列化问题,但这次是关于序列化为二进制时 Java 的本机序列化导入。我必须序列化在另一个 java 文件中生成的随机树。我知道序列化和反序列化是如何工作的,但是我在使用带有 java.io.Serializable 的二进制序列化时遵循的示例与使用简单对象时的方式不同。这是我的代码段:
import java.io.*;
import java.io.FileInputStream;
public class BinaryS
{
public static void main(String[] args) {
Tree randomTree = RandomTreeBuilder.randomTree(10);
FileOutputStream fOut=null;
ObjectOutputStream oOut=null;
try{
fOut= new FileOutputStream("/Users/Pat/programs/binaryfile.txt");
oOut = new ObjectOutputStream(fOut);
oOut.writeObject(randomTree); //serializing randomTree
System.out.println("An employee is serialized into /Users/Pat/binaryfile.txt");
}catch(IOException e){
e.printStackTrace();
}finally{
try {
oOut.flush();
oOut.close();
fOut.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
});
我相信问题出在我使用 writeObject(randomTree) 时。发生这种情况时,我会遇到一些终端异常……它们如下:
java.io.NotSerializableException:GeneralTree 在 java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1081) 在 java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:302) 在 BinaryS.main(BinaryS.java:24)
编辑:我知道它说的是 GeneralTree,但在课程开始时我把它放在了
print("public class RandomTreeBuilder implements java.io.Serializable");
然后,在它下面找到GeneralTree
print(" protected static Tree tree;
protected static ArrayList names;
//e6.1
/**
*Builds a random tree. The build method does the work.
*/
//b6.2
public static Tree randomTree(int n) {
// Create a random binary tree with n external nodes
tree = new GeneralTree();
names = NameGenerator.getNames();
build(tree.getRoot(), n); // auxiliary recursive method
return tree;
");
更新:嘿,伙计们,我发现了自己的问题,结果我是个白痴,没有意识到我必须下载一个额外的 .java 文件,现在很容易解决!谢谢你的帮助!