gpt4 book ai didi

java - 在 Java 中读取序列化对象时获取 EOFException

转载 作者:行者123 更新时间:2023-12-01 05:52:12 27 4
gpt4 key购买 nike

我有两种方法,一种是序列化对象,它工作正常:

public void record()throws RecordingException
{
ObjectOutputStream outputStream = null;
try
{
outputStream = new ObjectOutputStream(new FileOutputStream("src/data/employee.dat"));
outputStream.writeObject(this);
} catch (FileNotFoundException ex)
{
ex.printStackTrace();
throw new RecordingException(ex);
} catch (IOException ex)
{
ex.printStackTrace();
throw new RecordingException(ex);
}finally
{
try
{
if (outputStream != null) outputStream.close();
} catch (IOException ex){}
}
}

反序列化对象时出现的问题,我得到 EOFException!:

public final User loadObject(UserType usertype) throws InvalidLoadObjectException
{
ObjectInputStream istream = null;
String path = null;
if (usertype == UserType.EMPLOYEE)
{
path = "data/employee.dat";
}else if (usertype == UserType.CUSTOMER)
{
path = "data/customer.dat";
}else
throw new InvalidLoadObjectException("Object is not a sub class of User");

try
{
istream = new ObjectInputStream(ObjectLoader.class.getClassLoader().getResourceAsStream(path));

User u = loadObject(istream);
istream.close();
return u;
}catch (EOFException ex)
{
System.out.println(ex.getMessage());
return null;
}catch(Exception ex)
{
ex.printStackTrace();
throw new InvalidLoadObjectException(ex);
}
}

private User loadObject(ObjectInputStream stream) throws InvalidLoadObjectException
{
try
{
return (User) stream.readObject();
} catch (IOException ex)
{
ex.printStackTrace();
throw new InvalidLoadObjectException(ex);
} catch (ClassNotFoundException ex)
{
ex.printStackTrace();
throw new InvalidLoadObjectException(ex);
}
}

最佳答案

我不知道这是否是您问题的原因,但写入文件的代码有一个微妙的缺陷。在 finally block ,您关闭流并忽略任何异常。如果close()方法执行最终flush() ,那么刷新中抛出的任何异常都将不会被报告。

关于java - 在 Java 中读取序列化对象时获取 EOFException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4310839/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com