如何反序列化当前对象

问题描述 投票:0回答:1

我创建了一个bankStatement程序,它有两个类,例如MainFinancialManager。在此程序中,我可以提取,存款并查看当前的帐户余额。这是我的FinancialManager

import java.io.*;
import java.util.Vector;

public class FinancialManager implements Serializable {
    private double balance1;
    private Vector<String> statement1;
    public FinancialManager(){
        balance1=0;
        statement1 = new Vector<String>();
    }
    public void deposit(double value){
        balance1 = balance1+value;
        String st = "Deposit  "+String.valueOf(value);
        statement1.add(st);
    }
    public void withdraw(double value){
        if(value<balance1){
            balance1 = balance1 - value;
            String st = "Withdraw "+String.valueOf(value);
            statement1.add(st);
        }else{
            String st = "Withdraw 0.0";
            statement1.add(st);
        }
    }
    public String balance(){
        return String.valueOf(balance1);
    }
    public void statement(){
        String[] array = statement1.toArray(new String[statement1.size()]);
        for(int i=0;i<array.length;i++){
            System.out.println(array[i]);
        }
    }

    public void save(String fileName) throws IOException {
        try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(fileName))) {
            // write "this" - the current object - to the file
            objectOutputStream.writeObject(this);
        }
    }

}

我的主要班级在下面

public class Main {
    public static final Scanner scan = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        FinancialManager fm = new FinancialManager();
        fm.deposit(25.00);
        fm.withdraw(12.00);
        fm.deposit(10.00);
        fm.deposit(5.00);
        fm.withdraw(8.00);
        System.out.println("The current balance is "+fm.balance());
        fm.statement();
        fm.save("text.txt");

        FinancialManager anotherfm = new FinancialManager();

    }
}

我可以使用此关键字在FinancialManager中创建Serialization方法。但是我不知道如何创建Deserialization方法。我该怎么做?请帮助我。方法应该在FinancialManager类中。

public void load(String filename){
   //Write your code here
}

需要像这样在Main类中使用此方法

FinancialManager anotherFM = new FinancialManager(); 
anotherFM.load(laccountl");
anotherFM.statement();

我创建了一个bankStatement程序,它有两个类,例如Main和FinancialManager。在这个程序中,我可以提取,存款并查看当前的帐户余额。这是我的FinancialManager ...

java file serialization stream deserialization
1个回答
2
投票

反序列化将创建对象。该对象不应该存在。因此,请在static中进行创建,与创建方法相同(例如List.of)。

© www.soinside.com 2019 - 2024. All rights reserved.