【发布时间】:2019-09-02 15:23:32
【问题描述】:
我想使用 FileInputStream 和 ObjectInputStream 从文件中读取数据。我创建了实现 Externalizable 接口和 @overriden 两个方法的 BankAccount 类。我不明白为什么它会抛出 IOException。
这些是接口 Externalizable 的重写方法:
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
char a = in.readChar();
id = in.read();
username = (String)in.readObject();
name = (String)in.readObject();
password = (String)in.readObject();
amount = in.readDouble();
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeChar('A');
out.write(id);
out.writeObject(username);
out.writeObject(name);
out.writeObject(password);
out.writeDouble(0);
}
这是我在主类中调用这些方法的代码:
try
{
// Writing the object into file
FileOutputStream file = new FileOutputStream(path);
ObjectOutputStream out = new ObjectOutputStream(file);
// Method for serialization of object
out.writeObject(account);
out.close();
file.close();
}
catch(IOException ex)
{
System.out.println("IOException is caught");
}
try {
//Reading object from file
FileInputStream file = new FileInputStream(path);
ObjectInputStream out = new ObjectInputStream(file);
BankAccount bankk = (BankAccount)out.readObject();
System.out.println(bankk);
out.close();
file.close();
}
catch(IOException ex)
{
System.out.println("IOException is caught");
}
这是它扔的东西:
java.io.InvalidClassException: al.tct.bank_project.AdminAccount; no valid constructor
at java.io.ObjectStreamClass$ExceptionInfo.newInvalidClassException(ObjectStreamClass.java:157)
at java.io.ObjectStreamClass.checkDeserialize(ObjectStreamClass.java:862)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2038)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1568)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:428)
at al.tct.bank_project.BankApp$RegisterStage$1.writeToFile(BankApp.java:463)
at al.tct.bank_project.BankApp$RegisterStage$1.handle(BankApp.java:412)
at al.tct.bank_project.BankApp$RegisterStage$1.handle(BankApp.java:404)
【问题讨论】:
-
你能显示
IOException堆栈跟踪吗? -
请在您的问题中进行堆栈跟踪。不要调用输入流
out。 -
ex.printStackTrace()总是(除非它被记录) -
我发布了 IOException 堆栈跟踪...但我仍然不明白
-
这是一个
InvalidClassException,它的错误消息准确地说明了问题所在。
标签: java serialization ioexception objectinputstream objectoutputstream