我在程序开始时遇到了反序列化的问题。
public static void main(String[] args) throws IOException, ClassNotFoundException{
Test object = new Test(); // Test implements Serializable
//start
deserialize();
//do something
//end
serialize(object);
}
public static void deserialize()
{
test object = null;
try
{
FileInputStream file= new FileInputStream(".../Example.ser");
if(file.read()!=-1) //the first time the file will be empty
{
ObjectInputStream read= new ObjectInputStream(file); //here an exception is thrown the second time the program is started
object = (Test) read.readObject();
object .printdata();
read.close();
file.close();
}
else
{
file.close();
}
}catch(IOException i)
{
i.printStackTrace();
return;
}catch(ClassNotFoundException c)
{
c.printStackTrace();
return;
}
}
public static void serialize(Test object)
{
try
{
FileOutputStream file =
new FileOutputStream(".../Example.ser");
ObjectOutputStream write = new ObjectOutputStream(file );
write .writeObject(object);
write .close();
file .close();
}catch(IOException i)
{
i.printStackTrace();
}
}
如果切换序列化和反序列化,或者如果我在序列化后调用反序列化,该程序是有效的。
它第一次运行正常,但如果我第二次启动它反序列化@ ObjectInputStream read = new ObjectInputStream(file);抛出一个流恶化的异常。
在程序启动时,序列化文件必须反序列化并打印,正如我所说,如果切换调用然后将反序列化的调用复制回顶部它可以工作但不是如果它保持这样。它第一次运行但第二次抛出异常。
答案 0 :(得分:0)
if(file.read()!=-1) //the first time the file will be empty
问题出在这里。您正在阅读并丢弃文件的第一个字节,因此以下读取将不同步。去掉它。评论也不正确。第一次运行此代码时,文件将缺席,而不是空。如果您仍然需要测试零长度文件,只需单独捕获EOFException
,因为您只读取一个对象。
答案 1 :(得分:0)
如果这是学校作业,您必须坚持使用ObjectInputStream
/ ObjectOutputStream
序列化,请阅读此答案。但是,如果你可以使用你想要的任何序列化格式,那么我建议使用像JSON这样的非二进制格式。
json-io(https://github.com/jdereg/json-io)等库允许您使用一行将Java数据序列化为人类可读的JSON格式:
String json = JsonWriter.objectToJson(root);
并读入序列化的JSON数据:
Object root = JsonReader.jsonToJava(json);
能够查看序列化内容并阅读它在调试此类情况时非常有用。大多数现代IDE都可以轻松编辑JSON数据,还有一些网站,例如:http://www.jsoneditoronline.org/,允许您直接在浏览器中编辑JSON。