对于我的游戏,我将用户玩过的游戏数量存储在内部存储器中的文件中。这非常有效,直到存储了195之后,无论玩了多少游戏,它都不会增加。

public void saveNumGames(){
    Log.d("saveNumGames", "Called");
    int numGames;
    File numGamesFile = new File(mainActivity.getFilesDir(), "numGames");
    try {

        BufferedInputStream BIS = new BufferedInputStream(new FileInputStream(numGamesFile));
        numGames = BIS.read();
    }catch (Exception e) {
        e.printStackTrace();
        numGames = 0;
    }
    try{
        numGames++;
        Log.d("numGames", Integer.toString(numGames));
        FileOutputStream fos = new FileOutputStream(numGamesFile);
        PrintWriter PW = new PrintWriter(new OutputStreamWriter(fos));
        PW.write(numGames);
        PW.flush();
        PW.close();
        if(numGames==12){
            Games.Achievements.unlock(MainActivity.apiClient, "CgkIlcXhyp4YEAIQDA");
        } else if(numGames==50){
            Games.Achievements.unlock(MainActivity.apiClient, "CgkIlcXhyp4YEAIQDQ");
        }
    }catch (Exception e){
        e.printStackTrace();
    }
}


我的想法是,这是因为数字195是可存储在字节(或位?)中的最大值。如果是这样,我应该怎么做才能防止此数字上限发生。

最佳答案

首先您使用了两种错误的方法。首先是numGames = BIS.read(); read()方法设计为仅读取一个字节。另一个方法PW.write(numGames)方法write哪个参数int指定要写入的字符。
它应该工作:

  public static void saveNumGames() {
    Log.d("saveNumGames", "Called");
    int numGames;
    File numGamesFile = new File(mainActivity.getFilesDir(), "numGames");
    try {
        numGames = new Integer(new String(Files.readAllBytes(Paths.get(mainActivity.getFilesDir() + "numGames"))));
    } catch (Exception e) {
        e.printStackTrace();
        numGames = 0;
    }

    try (FileOutputStream fos = new FileOutputStream(numGamesFile)) {
        numGames++;
        Log.d("numGames", Integer.toString(numGames));
        PrintWriter PW = new PrintWriter(fos);
        PW.write(String.valueOf(numGames));
        PW.flush();
        PW.close();
        if (numGames == 12) {
            Games.Achievements.unlock(MainActivity.apiClient, "CgkIlcXhyp4YEAIQDA");
        } else if (numGames == 50) {
            Games.Achievements.unlock(MainActivity.apiClient, "CgkIlcXhyp4YEAIQDQ");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

07-26 02:04