Android: getFilesDir() 中保存的文件在应用程序重启后消失

Android: files saved inside getFilesDir() disappear after application restart

我想将文件保存到应用程序特定的存储空间,如 documentation 所示:

String filename = "myfile.txt";
String fileContents = "Hello world!";
try (FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE)) {
    fos.write(fileContents.toByteArray());
}

不幸的是,每次我重新启动应用程序时,所有数据都会丢失。

如何防止数据被删除?

请注意,我对使用 SharedPreferences/External Storage/Database 不感兴趣。 Android Studio 3.5.3.

您需要在使用完文件后将其关闭。否则不存入磁盘,只存入内存。 这就是为什么当您 "shut down" 应用程序并重新开始时,它不再存在的原因。

FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
    try  {
        fos.write(fileContents.toByteArray());
    } catch (IOException e) {
      e.printStackTrace();
    } finally{
       try{
       if (fos!=null){
          fos.flush();
          fos.close();
        }
       } catch( Exception e) {
         e.printStackTrace();
       }
    }