Android: 无法在文件中保存超过 195 个数

Android: Unable to save more than the number 195 in a file

对于我的游戏,我将用户玩过的游戏数量存储在内部存储器的文件中。这非常有效 - 直到存储数字 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 是一个字节(或位?)中可存储的最大值造成的。如果是这样,我应该怎么做才能防止出现此数量上限。

对于你想要实现的目标,我会使用 SharedPrefereces class ( SharedPreferences)

Saving key-value 是这个

的用法示例

一个字节是 8 位,因此您肯定需要更多的字节来存储 195 之类的任何内容。当 196 存储在文件中时,我很想知道以下内容。

这一行之后的 numGames 值是多少

numGames = BIS.read();

这打印了什么

Log.d("numGames", Integer.toString(numGames));

首先你使用两个方法wrong.First是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();
    }
}