相当于Java中的python的shelve模块

Java中的任何模块是否等同于python的搁置模块?我需要这个来实现像分类数据访问这样的字典.类字典分类数据访问是一种以持久的访问数据库格式保存
Python对象的强大方法.我需要一些东西用于相同的目的但是用Java. 最佳答案 我也需要这个,所以我写了一个.有点晚了,但也许它会有所帮助.

它没有实现close()方法,只是使用sync(),因为它只在实际写入时保持文件打开.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;

public class Shelf extends HashMap<String, Object> {
    private static final long serialVersionUID = 7127639025670585367L;
    private final File file;

    public static Shelf open(File file) {
    Shelf shelf = null;
    try {
        if (file.exists()) {
        final FileInputStream fis = new FileInputStream(file);
        ObjectInputStream ois = new ObjectInputStream(fis);
        shelf = (Shelf) ois.readObject();
        ois.close();
        fis.close();
        } else {
        shelf = new Shelf(file);
        shelf.sync();
        }
    } catch (Exception e) {
        // TODO: handle errors
    }
    return shelf;
    }

    // Shelf objects can only be created or opened by the Shelf.open method
    private Shelf(File file) {
    this.file = file;
    sync();
    }

    public void sync() {
    try {
        final FileOutputStream fos = new FileOutputStream(file);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(this);
        oos.close();
        fos.close();
    } catch (Exception e) {
        // TODO: handle errors
    }
    }

    // Simple Test Case
    public static void main(String[] args) {
    Shelf shelf = Shelf.open(new File("test.obj"));
    if (shelf.containsKey("test")) {
        System.out.println(shelf.get("test"));
    } else {
        System.out.println("Creating test string.  Run the program again.");
        shelf.put("test", "Hello Shelf!");
        shelf.sync();
    }
    }
}
点赞