问题描述
我正在尝试将int( score
)保存在真实设备的内部存储中,由于某种原因,当我加载它时,它会使score
等于0。
码:
public int score;
String scoreString = Integer.toString(score);
FileOutputStream fileOutputStream = null;
FileInputStream fileInputStream = null;
final TextView best = (TextView) findViewById(R.id.best);
// Save
try {
file = getFilesDir();
fileOutputStream = openFileOutput("record.txt", Context.MODE_PRIVATE);
fileOutputStream.write(scoreString.getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Toast.makeText(MainActivity.this, "Save() works fine " + scoreString + file, Toast.LENGTH_SHORT).show();
// load
try {
FileInputStream fileInputStream = openFileInput("record.txt");
int read = -1;
StringBuffer buffer = new StringBuffer();
while ((read = fileInputStream.read()) != -1){
buffer.append((char)read);
}
Log.i("ELY", buffer.toString());
String record = buffer.substring(0);
best.setText("Best: " + record);
Toast.makeText(MainActivity.this, "Load() OK " + record , Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
有人可以帮我吗?
谢谢
1楼
同时升级如果你只是想保存的分数,你可以使用SharedPrefernces
获得分数:
public int getScore() {
SharedPreferences pref = getApplicationContext().getSharedPreferences("MY_PREFS", context.MODE_PRIVATE);
return pref.getInt("SCORE", 0);
}
要存储分数:
public void setScore(int score) {
SharedPreferences pref = getApplicationContext().getSharedPreferences("MY_PREFS", context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("SCORE", score);
editor.commit();
}