我在defaultWriteObject上得到了NotActiveException,但我无法说明原因

时间:2018-04-06 17:40:23

标签: java exception serialization file-io outputstream

我在类I序列化中有一个writeObject方法,我在其中调用了defaultWriteObject。这有什么不对?字段密码是我尝试加密然后自己解密的瞬态字段。当我运行此代码时,我在defaultWriteObject()处获得NotActiveException。任何帮助将不胜感激,谢谢:)

public static void main(String[] args) throws IOException, 
  ClassNotFoundException {
    Account bankAccount;
    bankAccount = new Account("Person", 123456789, "Pa55word", 900);

    try {
    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("P:/Account.txt"));
    bankAccount.writeObject(out);
    out.close();
    Account otherAccount = new Account();

    ObjectInputStream in = new ObjectInputStream(new FileInputStream("P:/Account.txt"));
    otherAccount.readObject(in);
    in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private void writeObject(ObjectOutputStream out) throws IOException, ClassNotFoundException {
    out.defaultWriteObject();
    out.writeObject(encrypt(password));
}

private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    in.defaultReadObject();
    password = decrypt((String)in.readObject());
}

这是堆栈跟踪:

java.io.NotActiveException: not in call to writeObject
at java.io.ObjectOutputStream.defaultWriteObject(Unknown Source)
at Account.writeObject(Account.java:75)
at Account.main(Account.java:59)

1 个答案:

答案 0 :(得分:1)

问题出在这里:bankAccount.writeObject(out);

您需要将对象写入ObjectOutputStream,然后Serializable将调用方法writeObject并将其保存。

尝试:out.writeObject(bankAccount)