【发布时间】:2016-04-20 13:50:35
【问题描述】:
当我使用 readObject 时,我得到 OptionalDataException(当流中的下一个元素是原始数据时,试图读取一个对象),我该如何解决这个问题?页面是可序列化的。 writeObject 有效。
public Map<Long,Page<byte[]>> readAllPages(){
ObjectInputStream in = null;
try
{
in= new ObjectInputStream(new FileInputStream(HardDisk.getDefault_File_Name()));
@SuppressWarnings("unchecked")
Map<Long, Page<byte[]>> readMap = (Map<Long, Page<byte[]>>)in.readObject(); // exception here
return readMap;
}
catch(Exception ex)
{
ex.printStackTrace();
System.exit(0);
return null;
}
finally
{
if(in != null)
{
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void writeAllPages(Map<Long,Page<byte[]>> hd){
ObjectOutputStream out = null;
try
{
out = new ObjectOutputStream(new FileOutputStream(HardDisk.getDefault_File_Name()));
out.writeObject(hd);
}
catch(Exception ex)
{
ex.printStackTrace();
System.exit(0);
}
finally
{
if(out != null)
{
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
【问题讨论】:
-
Page是否有自定义读取和/或写入方法? -
什么意思?页面有 getter 和 setter,但没有 write 或 read 方法
-
您是否尝试反序列化在
Page类不同时序列化的对象? -
不,这些是代码中唯一使用 readObject 和 writeObject 的地方。
-
我已经删除了文件并使用writeObject再次创建它,没有问题然后使用readAllPages方法,问题仍然存在。我添加了调用方法的代码。
标签: java objectinputstream optionaldataexception