【问题标题】:I'm getting a NotActiveException at defaultWriteObject and I can't tell why我在 defaultWriteObject 处收到 NotActiveException,但我不知道为什么
【发布时间】:2018-04-06 17:40:22
【问题描述】:

我在序列化的类中有一个 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)

【问题讨论】:

  • 你能发布完整的 stackTrace 吗?
  • @GBlodgett 我将其添加到问题中
  • main 中的哪一行导致了错误?
  • @GBlodgett bankAccount.writeObject(out);在 main 方法中,out.defaultWriteObject();在 writeObject 方法中。

标签: java exception serialization file-io outputstream


【解决方案1】:

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

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

尝试:out.writeObject(bankAccount)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-14
    • 2020-08-02
    • 1970-01-01
    • 2020-03-20
    • 1970-01-01
    • 2013-09-08
    • 2013-09-13
    相关资源
    最近更新 更多