简体   繁体   中英

I'm getting a NotActiveException at defaultWriteObject and I can't tell why

I have a writeObject method in the class I'm serializing, and I'm calling defaultWriteObject in it. What is wrong here? The field password is the transient field that I'm trying to encrypt then decrypt on my own. When I run this code, I get a NotActiveException at defaultWriteObject(). Any help would be appreciated, thanks :)

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());
}

Here is the stack trace:

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)

The problem is in here: bankAccount.writeObject(out);

You need to write your Object into ObjectOutputStream than Serializable will call your method writeObject and will save it.

Try to : out.writeObject(bankAccount)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM