我想保存一个文件" xp.txt"跟踪用户在游戏中的体验。如果文件不存在,我想创建它并写下" 0"在文件中(表示0经验)。如果文件存在,我想从中读取并将exp保存到java类中的int变量。而且我也想知道如何改变" 0"其他一些价值。
提前致谢!
我目前的代码是:
try {
OutputStreamWriter out = new OutputStreamWriter(openFileOutput(XP, 0));
out.write("0");
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
InputStream in = openFileInput(XP);
if (in != null) {
InputStreamReader temp = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(temp);
String str;
StringBuilder buf = new StringBuilder();
while ((str = reader.readLine()) != null) {
xp = Integer.parseInt(str);
System.out.println(xp);
}
in.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
但是我找不到文本文件,它并没有像我预期的那样工作。
答案 0 :(得分:0)
您可以使用以下方式存储数据
我认为您的用例SharedPreferences
会有用。一个简单的例子是
保存值
SharedPreferences.Editor editor = getSharedPreferences("unique_name", MODE_PRIVATE).edit();
editor.putInt("xp", 10);
editor.commit();
要检索值
SharedPreferences prefs = getSharedPreferences("unique_name", MODE_PRIVATE);
int xp = prefs.getInt("xp", 0); // will return 0 if no value is saved
您可以从此here了解更多信息。