0

我正在开发一款安卓游戏。我有一个扩展 View 的 Game 类和一个 Main Activity 类。

我正在尝试从内部存储中加载高分。我希望它在 onCreate() 中加载并保存在 onDestroy() 中。

Game game;
FileOutputStream fos;
FileInputStream fis;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    game = new Game(this);

    String collected = null;

    try {
        File file = getBaseContext().getFileStreamPath(Game.FILE_NAME);
        if(!file.exists()){
            file.createNewFile();
        }

        fis = openFileInput(Game.FILE_NAME);
        byte[] dataArray = new byte[fis.available()];
        while (fis.read(dataArray) != -1){
            collected = new String(dataArray);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally{
        try {
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    if(collected != null) game.setHighScore(Integer.parseInt(collected));
    else game.setHighScore(0);
    setContentView(game);
    }

protected void onDestroy() {
    super.onDestroy();

    try {
        fos = openFileOutput(Game.FILE_NAME, Context.MODE_PRIVATE);
        String data = "" + game.highScore;
        fos.write(data.getBytes());
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally{
        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}



}

我正在我的 DroidX 上测试该应用程序。它在尝试读取文件时在启动时崩溃。如果我注释掉该部分以阅读它,该应用程序将运行良好并按应有的方式写入数据。如果我在保存数据时再次运行,它会正确加载。

在尝试加载文件之前如何检查文件是否存在?

提前感谢

4

1 回答 1

0

切换到使用SharedPreferences,它是为这个用例设计的。

这是一个例子来说明它是多么容易:

public class Example extends Activity {
    public static final String PREFS_NAME = "MyPrefsFile";

    @Override
    protected void onCreate(Bundle state){
       super.onCreate(state);
       . . .

       // Restore preferences
       SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
       // Get highScore if it exists, otherwise default to zero
       int highScore = settings.getInt("highScore", 0);
       setHighScore(highScore);
    }

    @Override
    protected void onStop(){
       super.onStop();

      // We need an Editor object to make preference changes.
      // All objects are from android.context.Context
      SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
      SharedPreferences.Editor editor = settings.edit();
      editor.putInt("highScore", mHighScore);

      // Commit the edits!
      editor.commit();
    }
}
于 2012-06-03T01:58:06.213 回答