我想使用FileInputStream和ObjectInputStream从文件中读取。我创建了BankAccount类,它实现了Externalizable接口和@overriden两种方法。我不明白它为什么抛出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)
Stack Traces包含至少4个有趣的信息:
[1]类型。 IOException有子类。也许它是一个FileNotFoundException。
[2]堆栈跟踪。这是一行指向源文件中发生错误的位置,以及导致此方法执行的“调用链”。
[3]消息。例外情况可以通过可读的英语解释更多信息。
[4]因果链。异常可能有原因,通常该异常本身也很有趣(并且该原因可能有原因)。
还有更多(例如抑制链)。
如果您遇到异常并试图打印它,那么你就会搞乱,打印所有这很难做到但这一切都很重要。
所以,除非你能真正处理它,否则不要捕获异常。打印错误消息或记录它不处理它。
在这里,只需将您的方法声明为'throws IOException'。如果这是不可能的(只有当您从超类/接口扩展/实现方法时才会发生这种情况),那么“我不知道该怎么做”代码是这样的:
catch (ExceptionICannotHandle e) {
throw new RuntimeException(e);
}
这是保证你获得信息的唯一方法。
我建议你更新你的代码,然后你就会明白这个错误的原因。