Android - 保存Int on Internal Storage错误

时间:2015-07-19 11:44:34

标签: java android internal-storage

我正在尝试在实际设备的内部存储上保存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 个答案:

答案 0 :(得分: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();
}