文件消失,又重新出现

File disappears, and re-appears

我在商店中有一个 android 应用程序可以在文件中保存一些键值对(见下文)。最近我想对应用程序做一个小更新(一些字体和颜色,没有逻辑),我注意到在更新的应用程序中文件丢失了。然后我卸载了应用程序并再次从 Play 商店安装了旧版本,数据又在那里了。为什么更新后的版本数据丢失了?

要将内容保存到我使用的文件中:

public void commit() {
    OutputStream outputStream;
    try {
        File file = mContext.getFileStreamPath(FILENAME);
        if (file.exists()) {
            file.createNewFile();
        }

        outputStream = mContext.openFileOutput(FILENAME, Context.MODE_PRIVATE);
        ObjectOutputStream objectoutputstream = new ObjectOutputStream(outputStream);

        String json = new Gson().toJson(mAppsettings, AppSettings.class);
        objectoutputstream.writeObject(json);
        objectoutputstream.close();
        outputStream.close();
    } catch (IOException e) {
        LogUtils.v("Saving failed with IOException\n" + e.getLocalizedMessage());
    }
}

要加载保存的数据,我使用以下方法:

private void load() {
    InputStream inputStream;
    try {
        File file = mContext.getFileStreamPath(FILENAME);
        if (!file.exists()) {
            mAppsettings = new AppSettings();
            return;
        }

        inputStream = mContext.openFileInput(FILENAME);
        ObjectInputStream objectinputstream = new ObjectInputStream(inputStream);
        String json = (String) objectinputstream.readObject();
        mAppsettings = new Gson().fromJson(json, AppSettings.class);

        objectinputstream.close();
        inputStream.close();
    } catch (IOException e) {
        LogUtils.v("Settings: load(): IOException\n" + e.getMessage());
    } catch (ClassNotFoundException e) {
        LogUtils.v("Settings: load(): ClassNotFoundException\n" + e.getMessage());
    }
}

我更新了

  • compileSDKVersion 从 25 -> 27
  • minSdkVersion 从 9 -> 14
  • 删除了 buildToolsVersion

问题不再出现。我不知道问题到底是什么以及为什么它不再是问题了。无论如何,感谢您的帮助!