我正在编写一个小游戏,我想在SD卡上保存分数和音量(启用或禁用) 我的两个函数的代码是:
public static void load(FileIO files) {
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(
files.readFile(".save")));
soundEnabled = Boolean.parseBoolean(in.readLine());
for (int i = 0; i < 5; i++) {
highscores[i] = Integer.parseInt(in.readLine());
}
} catch (IOException e) {
// :( It's ok we have defaults
} catch (NumberFormatException e) {
// :/ It's ok, defaults save our day
} finally {
try {
if (in != null)
in.close();
} catch (IOException e) {
}
}
}
// -----------------------
public static void save(FileIO files) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
files.writeFile(".save")));
out.write(Boolean.toString(soundEnabled));
for (int i = 0; i < 5; i++) {
out.write(Integer.toString(highscores[i]));
}
} catch (IOException e) {
} finally {
try {
if (out != null)
out.close();
} catch (IOException e) {
}
}
}
程序运行时此代码没问题,但如果我重启设备,则分数会丢失。 你知道为什么吗?
谢谢!
ps:FileIO类是:
public class AndroidFileIO implements FileIO {
Context context;
AssetManager assets;
String externalStoragePath;
public AndroidFileIO(Context context) {
this.context = context;
this.assets = context.getAssets();
this.externalStoragePath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + File.separator;
}
public InputStream readAsset(String fileName) throws IOException {
return assets.open(fileName);
}
public InputStream readFile(String fileName) throws IOException {
return new FileInputStream(externalStoragePath + fileName);
}
public OutputStream writeFile(String fileName) throws IOException {
return new FileOutputStream(externalStoragePath + fileName);
}
public SharedPreferences getPreferences() {
return PreferenceManager.getDefaultSharedPreferences(context);
}
}
答案 0 :(得分:1)
这里有两个问题。首先,out.write不会在每次调用结束时插入换行符,您必须手动执行此操作。所以当你在cal中执行readline来解析你实际消耗文件中所有数据的布尔值时,会发生什么。其次,在离开该函数之前,需要刷新并关闭文件,以确保不在缓冲区中留下任何数据。
这是保存重写应该有效:
public static void save(FileIO files) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
files.writeFile(".mrnom")));
out.write(Boolean.toString(soundEnabled));
out.write("\n");
for (int i = 0; i < 5; i++) {
out.write(Integer.toString(highscores[i]));
out.write("\n");
}
out.flush();
out.close();
} catch (IOException e) {
} finally {
try {
if (out != null)
out.close();
} catch (IOException e) {
}
}
}
答案 1 :(得分:0)
我是第一次编程但是使用共享的prefs解决了这个问题。这样可以避免在更新应用程序时丢失数据。