如何在序列化时阻止此反序列化对象变为null?

时间:2013-05-01 01:41:37

标签: java serialization null deserialization

我正在编写一个简单的银行程序,它为用户提供了一个非常简单的GUI来处理一个简单的银行帐户,其中包含余额和所有者名称等变量。由于程序仅运行在单个银行帐户中,因此每次程序启动时都会对帐户(对象)进行反序列化。这就是我的问题所在:每次我的帐户对象被反序列化时,它变为null。我试着四处寻找这个,只想得出空洞的结果。我该如何防止这种情况?我觉得这个问题比我想象的更容易解决,但我不确定为什么会这样。为什么account对象不作为帐户返回?我将在下面发布两个课程......

BankGUI课程:

package GUIs;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.UIManager;

public class BankGUI implements Serializable {

    BankAccount account;
    static BankGUI gui;

    private void deserializeAccount() {
        try {
            ObjectInputStream objectStream2 = new ObjectInputStream(
                    new FileInputStream("bankAccounts.txt"));
            Object acc = objectStream2.readObject();
            account = (BankAccount) acc;
            System.out.println("yes");
            objectStream2.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Nope.");
        }
    }

    private void checkForNull() {
        if (account == null) {
            System.out.println("It's been nullified.");
        } else {
            System.out.println("It worked.");
        }
    }
    public static void main(String[] args) {
        System.out.println("");
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        gui = new BankGUI();
        gui.deserializeAccount();
        gui.checkForNull();
        gui.displayGUI();
    }

    // all global components for JFrame
    JTextArea statusArea;
    JCheckBox isLockedCheckBox;
    JList depositAmount;
    JList withdrawAmount;
    JButton depositButton;
    JButton withdrawButton;
    JButton saveAccountButton;

    private void displayGUI() {
        JFrame frame = new JFrame("Virtual Bank v3.3");

        Integer[] intList = { 1, 2, 5, 10, 20, 50 };

        JPanel rightPanel = new JPanel();
        rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
        rightPanel.setBackground(Color.GREEN);

        JPanel centerPanel = new JPanel();
        centerPanel.setBackground(Color.GREEN);
        centerPanel.setLayout(new GridBagLayout());

        frame.add(BorderLayout.CENTER, centerPanel);
        frame.add(BorderLayout.EAST, rightPanel);

        // add some JLabel's
        JLabel depositAmountLabel = new JLabel("Deposit Amount:");
        JLabel withdrawAmountLabel = new JLabel("Withdraw Amount:");
        JLabel isLockedLabel = new JLabel("Lock account(True/False)");

        // finish components(center panel)
        statusArea = new JTextArea(25, 25);
        statusArea.setEditable(false);

        centerPanel.add(statusArea);

        // add this to panel
        isLockedCheckBox = new JCheckBox();
        // add this to panel

        // scrollers and Jlists
        // ***********************************************************************
        depositAmount = new JList(intList);
        JScrollPane scroller1 = new JScrollPane(depositAmount);
        scroller1
                .setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scroller1
                .setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        depositAmount.setVisibleRowCount(1);
        depositAmount.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        withdrawAmount = new JList(intList);
        JScrollPane scroller2 = new JScrollPane(depositAmount);
        scroller2
                .setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scroller2
                .setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        depositAmount.setVisibleRowCount(1);
        depositAmount.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        // ***********************************************************************

        depositButton = new JButton("Deposit Amount.");
        withdrawButton = new JButton("Withdraw Amount");
        saveAccountButton = new JButton("Save your Account");

        rightPanel.add(depositAmount);
        rightPanel.add(depositButton);

        frame.setSize(425, 650);
        frame.setVisible(true);
    }

    private void serializeAccount() {
        try {
            ObjectOutputStream objectStream1 = new ObjectOutputStream(
                    new FileOutputStream("bankAccounts.txt"));
            objectStream1.writeObject(account);
            objectStream1.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

BankAccount类:

package GUIs;

import java.io.Serializable;

public class BankAccount implements Serializable {

    private static final long serialVersionUID = -5341449653011848470L;

    int balance = 0;
    int userWallet = 0;
    String owner = "Foo Bar";

    String status = "Account Owner: " + owner + "\nAccount balance: $"
            + balance + "\nOwner Wallet Balance: $" + userWallet;
    boolean isLocked = false;

    public int withdraw(int amount) {
        balance -= amount;
        userWallet += amount;
        return userWallet;
    }

    public int deposit(int amount) {
        balance += amount;
        userWallet -= amount;
        return balance;
    }

    public int depositCashIntoWallet(int amount) {
        userWallet += amount;
        return userWallet;
    }

}

1 个答案:

答案 0 :(得分:1)

这个问题很可能会被重复关闭。

在此之前,运行这个小应用程序来重写银行帐户详细信息文件:

public class WriteBankDetails {

   public static void main(String[] args) throws IOException {
     ObjectOutputStream objectStream1 = 
                new ObjectOutputStream(new FileOutputStream("bankAccounts.txt"));
        objectStream1.writeObject(new BankAccount());
        objectStream1.close();

    }
}

这将确保文件没有损坏或包含以前版本的BankAccount。然后重新运行Swing应用程序。