Singleton Serializable Database 保存方法抛出 IOException

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

这个类的目标是能够在程序启动时加载并在数据更改时保存。我以前使用过这些相同的方法,即保存和加载方法。出于某种原因,我现在无法让它工作?有什么想法吗?

package BackEnd;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
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 java.util.Hashtable;


public class DataBase implements Serializable{
    
    private static final long serialVersionUID = 1L;

    private static Hashtable<String, Account> accountTable = new Hashtable<String, Account>();
    
    private static int nextAccountid = 1;
    
    private static DataBase instance = new DataBase();
    
    AccountInstance account = AccountInstance.getInstance(); 
    
    private DataBase() {
        
    }
    
    public static DataBase getInstance() {
        
        return instance;
    }
    
    public static DataBase load() {
        try (ObjectInputStream ois = new ObjectInputStream(
                new BufferedInputStream(new FileInputStream(new File("./src/Data/data.dat"))))) {
            instance = (DataBase) ois.readObject();
            System.out.println("load");
        } catch (IOException | ClassNotFoundException e) {
            getInstance();
            System.out.println("error load");
        }
        return instance;
    }
    
    public static void save() {
        try (ObjectOutputStream oos = new ObjectOutputStream(
                new BufferedOutputStream(new FileOutputStream(new File("./src/Data/data.dat"))))) {
            oos.writeObject(instance);
            System.out.println("Save");
        } catch (IOException e) {
            System.out.println("Error Save");
        }
    }
    

保存和加载方法不起作用,我做错了什么?

java serialization objectinputstream objectoutputstream
© www.soinside.com 2019 - 2024. All rights reserved.