How can I Serialize an object as a method inside the same object in java?

Jeewantha Lahiru :

I have created a simple Bank statement program in java. There is a class called FinancialManager and it controls someones bank statement. FinancialManager class is below.

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
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]);
        }
    }
}

The main class is below.

public class Main {
    public static void main(String[] args) {
        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();

    }
}

I need to Add a method called save and that method should be able to Serialize the object. As an example when I use that method like this in main method,

fm.save("test.ser");

It should be able to serialize the object to the "test.ser" file.How can I do that?

Joni :

The easy thing to do is create an ObjectOutputStream that writes to a file. For example:

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

To read it back in, use ObjectInputStream:

    public static FinancialManager open(String fileName) throws IOException, ClassNotFoundException {
        Path filePath = Path.of(fileName);
        try (ObjectInputStream objectInputStream = new ObjectInputStream(Files.newInputStream(filePath))) {
            return (FinancialManager) objectInputStream.readObject();
        }
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=356126&siteId=1