Java中有没有与python的搁置模块等效的模块?我需要这个来实现分类数据访问等字典。类似字典的分类数据访问是一种以持久易于访问的数据库格式保存 Python 对象的强大方法。我需要一些用于相同目的但在 Java 中的东西。
问问题
971 次
2 回答
2
我也需要这个,所以我写了一个。有点晚了,但也许会有所帮助。
它没有实现 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();
}
}
}
于 2013-04-30T20:33:00.807 回答
0
您可以使用像Jackson这样的序列化库,它将 POJO 序列化为 JSON。
教程中的一个例子:
Jackson 的 org.codehaus.jackson.map.ObjectMapper “正常工作”,可将 JSON 数据映射到普通的旧 Java 对象(“POJO”)。例如,给定 JSON 数据
{
"name" : { "first" : "Joe", "last" : "Sixpack" },
"gender" : "MALE",
"verified" : false,
"userImage" : "Rm9vYmFyIQ=="
}
需要两行 Java 代码才能将其转换为 User 实例:
ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
User user = mapper.readValue(new File("user.json"), User.class);
User 类看起来像这样(来自Tatu 博客上的条目):
public class User {
public enum Gender { MALE, FEMALE };
public static class Name {
private String _first, _last;
public String getFirst() { return _first; }
public String getLast() { return _last; }
public void setFirst(String s) { _first = s; }
public void setLast(String s) { _last = s; }
}
private Gender _gender;
private Name _name;
private boolean _isVerified;
private byte[] _userImage;
public Name getName() { return _name; }
public boolean isVerified() { return _isVerified; }
public Gender getGender() { return _gender; }
public byte[] getUserImage() { return _userImage; }
public void setName(Name n) { _name = n; }
public void setVerified(boolean b) { _isVerified = b; }
public void setGender(Gender g) { _gender = g; }
public void setUserImage(byte[] b) { _userImage = b; }
}
于 2013-01-24T14:39:08.120 回答