Serializable类不恢复状态

时间:2012-08-21 09:49:52

标签: java serialization deserialization

人为错误。以下代码没有错误

版主:请删除此内容。如果可能的话,请将我的25个声誉发送给Peter Lawrey,因为他帮助了我很多,甚至阅读了大量的日志数据。谢谢!

嗨,我遇到了Serializable数据库的问题。

关闭程序后(通过注销按钮),应该存储数据库。这是代码:

FileOutputStream f_out = null;
        try {
            f_out = new FileOutputStream("database.data");
            ObjectOutputStream obj_out = new ObjectOutputStream(f_out);
            obj_out.writeObject(database);
            System.out.println("Stored!");

        } catch (Exception ex) {
            Logger.getLogger(BankMainFrameGUI.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        } finally {
            try {
                f_out.close();
            } catch (IOException ex) {
                Logger.getLogger(BankMainFrameGUI.class.getName()).log(Level.SEVERE, null, ex);
                JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
        new BankMainFrameGUI();
        this.dispose();

然后使用以下代码恢复数据库:

    try {
        FileInputStream f_in = new FileInputStream("database.data");
        ObjectInputStream obj_in = new ObjectInputStream(f_in);
        database = (BankSystem) obj_in.readObject();
        System.out.println("FOUND!");
    } catch (Exception e) {
        System.out.println("New database!");
        database = new BankSystem();
    }

数据库及其所有内部类已设置为可序列化。但是,重新启动程序后,所有数据都将丢失(客户端,帐户,事务)。但是,数据库仍被检测为“发现!”语句显示在我的编译器的CLI中,但不显示在“新数据库”中。言。

我使用了链接列表和数组列表。

非常感谢你!我将对所有可行的解决方案进行升级。

SPOILER:很多可能无法获取的信息

如果需要,可提供额外信息:

Main BankSystem() constructor + important variables:

public class BankSystem implements Serializable {
    Transaction transactionManager;
    Identity identityManager;
    Account accountManager;
    dayFirstTransaction dayFirstTransactionManager;


    public BankSystem() {
        transactionManager = new Transaction();
        identityManager = new Identity();
        accountManager = new Account();
        dayFirstTransactionManager = new dayFirstTransaction();
    }
...

LinkedList节点的示例:

class Transaction implements Serializable { //Database for TransactionNode
    TransactionNode lastTransaction = null;
    long lastTransactionId = -1;

    //Unchangable location settings defined. Prevents ability to manipulate timestamp by changing computer clock. Acts as a security feature.
    //Timestamps are also finalised to ensure security (prevent manipulation)
    final TimeZone tz = TimeZone.getTimeZone("Singapore");
    final Locale lc = new Locale("en", "SG");
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS EEEE");
    final private Calendar cal = Calendar.getInstance(tz, lc);

    public long newTransaction(dayFirstTransaction dFTM,
            Client identity, AccountNode account, boolean action, long actionAmount, 
            String location, String comments) throws IOException {
        //Setting timings
        long timeMilli = cal.getTimeInMillis();
        String timeStamp = dateFormat.format(cal.getTime());

        TransactionNode previous = lastTransaction;
        TransactionNode previousUserTransaction = account.GetLastTransaction();

        long transactionId = ++lastTransactionId;

        long initialBalance = account.getBalance();
        long finalBalance;
        if(action) {
            finalBalance = initialBalance + actionAmount;
        } else {
            if(initialBalance < actionAmount) throw new IOException("There is not enough funds present in account " + account.accountId + ". \nAvailable balance: $" + account.getBalance());
            finalBalance = initialBalance - actionAmount;
        }

        lastTransaction = new TransactionNode(previous, previousUserTransaction, timeMilli, timeStamp,  
            transactionId, identity, account, action, actionAmount, 
            initialBalance, finalBalance, location, comments);

        dFTM.checkTransaction(lastTransaction);
        account.setLastTransaction(lastTransaction);
        return transactionId;
    }

        public void newTransaction (dayFirstTransaction dFTM, long timeMilli, String timeStamp,  
            Client identity, AccountNode account, boolean action, long actionAmount, 
            long initialBalance, long finalBalance, String location, String comments) throws IOException {

        TransactionNode previous = lastTransaction;
        TransactionNode previousUserTransaction = account.GetLastTransaction();

        long transactionId = ++lastTransactionId;

        lastTransaction = new TransactionNode(previous, previousUserTransaction, timeMilli, timeStamp,  
            transactionId, identity, account, action, actionAmount, 
            initialBalance, finalBalance, location, comments);

        dFTM.checkTransaction(lastTransaction);
        account.setLastTransaction(lastTransaction);
    }
...

此链表的节点:

class TransactionNode implements Serializable {
    //Node direction pointers
    final private TransactionNode previous;
    final private TransactionNode previousUserTransaction;

    //Declarations
    //For action:
    final public boolean CREDIT = true;
    final public boolean DEBIT = false;

    //Variables for each transaction
    final public long timeMilli; //Automated. For time comparisons
    final public String timeStamp;//Automated. For user reference
    final public long transactionId; // Automated at Transaction LinkedList
    final public Client identity;
    final public AccountNode account;
    final public boolean action; //true: Credit. false:Debit
    final public long actionAmount;
    final public long initialBalance;
    final public long finalBalance;
    final public String location;
    final public String comments;

    public TransactionNode(TransactionNode previous, TransactionNode previousUserTransaction, long timeMilli, String timeStamp,  
            long transactionId, Client identity, AccountNode account, boolean action, long actionAmount, 
            long initialBalance, long finalBalance, String location, String comments) {
        this.previous = previous;
        this.previousUserTransaction = previousUserTransaction;
        this.timeMilli = timeMilli;
        this.timeStamp = timeStamp;
        this.transactionId = transactionId;
        this.identity = identity;
        this.account = account;
        this.action = action;
        this.actionAmount = actionAmount;
        this.initialBalance = initialBalance;
        this.finalBalance = finalBalance;
        this.location = location;
        this.comments = comments;
    }

    //Getters & setters
    public TransactionNode getPreviousTransaction() {
        return previous;
    }

    public TransactionNode getPreviousUserTransaction() {
        return previousUserTransaction;
    }

}

4 个答案:

答案 0 :(得分:1)

你确定你没有触发这个:

catch (Exception e) {
   System.out.println("New database!");
   database = new BankSystem();
}

至少打印出与上述相关的异常和堆栈跟踪,即使它没有被触发。

我还会检查您写出的文件是否正在创建,并且是非零大小。这将为您提供一些指示,说明数据是否正在写入(当心 - 可能不完整)或未被读取。

答案 1 :(得分:1)

最可能的原因是您没有关闭您写入的流。 ObjectOutputStream是缓冲的,如果你关闭它正在写入的文件而不是关闭它,你将不会写入所有数据,当你尝试读取它时,你会得到一个例外。

答案 2 :(得分:1)

} catch (Exception e) {
    System.out.println("New database!");
    database = new BankSystem();
}

这是一个主要问题。这是处理反序列化异常的荒谬方式。您不是记录实际异常并中止,而是:

  1. 完全忽略实际的异常,这是唯一的信息来源,指出实际出现了什么问题。

  2. 继续进行,好像什么也没发生过。

  3. 继续使用空数据库而不是空数据库,这样可以让应用程序的其余部分继续运行,就好像除了神秘的数据库之外没有任何问题一样。

  4. 我根本不会抓住那个例外。我会让它在构造函数中一直冒出来,甚至可能是main()方法。

答案 3 :(得分:0)

  1. 关闭流
  2. 确保每个类都实现serializable我们ClientAccountNode
  3. 看不到几个类
  4. 在每个例外中使用printStackTrace()方法。