在java中存储本地数据? [英] Store local data in java?
问题描述
我正在使用 Java 进行简单的文本冒险.我希望能够定义每个任务的进度,并将其存储在用户的应用程序数据中的某个位置,以便他们下次玩游戏时读取.我该怎么做?
I am using Java to make a simple text adventure. I want to be able to define progress each mission, and that will store somewhere in the user's appdata to be read next time they play the game. How can I do this?
推荐答案
如果您只想在内部存储数据(即,跨会话保存,但不是用户可读的文件),我会使用 首选项 API.
If you just want to store the data internally (i.e., save across sessions, but not as a user-readable file), I would use the Preferences API.
例如:假设您有一个名为 MissionInfo
的类,它实现了 java.io.Serializable
.您可以执行以下操作:
For example: consider that you have a class called MissionInfo
which implements java.io.Serializable
. You could do the following:
// Precondition: missionInfoToSave is an variable of type MissionInfo
// The key used to store the data.
final String key = "SAVE_DATA";
// Get the preferences database for this package.
Preferences prefs = Preferences.userNodeForPackage(MissionInfo.class);
// To save, write the object to a byte array.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(missionInfoToSave); // write it to the stream
prefs.putByteArray(key, baos.toByteArray());
} catch (IOException ie) {
System.err.println("Failed to save to file");
}
// To load, read it back.
// The second argument is the default if the key isn't found.
byte[] stored = prefs.getByteArray(key, null);
if (stored == null) {
// There's no stored data.
return;
}
ByteArrayInputStream bais = new ByteArrayInputStream();
try {
ObjectInputStream ois = new ObjectInputStream(bais);
Object o = ois.readObject();
if (o instanceof MissionData) {
// Good: it's a saved data file.
updateMissionProgress((MissionData) o); // assuming this is defined
}
} catch (IOException ie) {
System.err.println("Couldn't load from prefs");
} catch (ClassNotFoundException cnfe) {
System.err.println("Class couldn't be found");
}
首选项 API 将跨会话存储数据.您可以在包 java.util.prefs
.
The Preferences API will store the data across sessions. You can find it in the package java.util.prefs
.
这篇关于在java中存储本地数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!