【发布时间】:2015-01-14 09:50:49
【问题描述】:
我在程序开始时遇到反序列化问题。
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);引发流损坏的异常。
在程序启动时,必须对序列化文件进行反序列化和打印,正如我所说,如果切换调用,然后将反序列化的调用复制回顶部,它可以工作,但如果它保持这样就不行。第一次运行但第二次抛出异常。
【问题讨论】:
-
测试类没有任何变量要存储在 .ser 文件中?你有没有在测试类本身初始化它们?您在用于序列化的对象中的值是多少
-
在序列化清空文件时尝试
FileOutputStream file = new FileOutputStream(".../Example.ser",false);。 -
你有在那个路径上生成的 .ser 文件吗?当你没有那个 .ser 文件时,你会得到流损坏的异常
-
@KalaiarasanManimaran 不,如果文件不存在,他会得到
FileNotFoundException。您无法从不存在的文件中获取任何类型的流,无论是否损坏。 -
@PabloGallegoFalcón
new FileOutputStream(String)在第二个参数为 false 时等价于new FileOutputStream(String, boolean)。
标签: java serialization exception-handling