【问题标题】:Android - Persist file when app closesAndroid - 应用关闭时保留文件
【发布时间】:2010-06-14 16:13:46
【问题描述】:

我正在我的 Android 应用程序中创建一个文件,如下所示:


HEADINGSTRING = new String("Android Debugging " + "\n"
                    "XML test Debugging");

}

public void setUpLogging(Context context){

    Log.d("LOGGING", "Setting up logging.....");
    try { // catches IOException below

         FileOutputStream fOut = context.openFileOutput(FILE_NAME,Context.MODE_APPEND);

         OutputStreamWriter osw = new OutputStreamWriter(fOut); 

         // Write the string to the file

         osw.write(HEADINGSTRING);

        /* ensure that everything is

        * really written out and close */

        osw.flush();

       osw.close();

} catch (FileNotFoundException e) {

    e.printStackTrace();
} catch (IOException e) {

    e.printStackTrace();
}
    finally{
        Log.d("LOGGING", "Finished logging setup.....");
    }
}

我在应用程序运行期间写入文件如下:


public void  addToLog(File file, String text) throws IOException {

         BufferedWriter bw = new BufferedWriter (new FileWriter(file, true));

         bw.write ("\n" + text);

         bw.newLine();

         bw.flush();
         bw.close();
}

这工作正常,但是当我的应用程序关闭时,文件被删除,当应用程序再次运行时,我写给它的所有信息都消失了。

如何确保应用程序关闭后文件仍然存在?

更新:

我已将 MODE_PRIVATE 更改为 MODE_APPEND,问题已解决,感谢 Skirmish。

【问题讨论】:

    标签: java android file outputstream bufferedwriter


    【解决方案1】:

    您可能需要检查http://developer.android.com/reference/android/content/Context.html#openFileOutput(java.lang.String, int) 尤其是关于 MODE_APPEND 的部分,而不是每次应用启动时都清除所有内容。

    【讨论】:

    • 这行得通,但是当我尝试再次使用 Mode_Private 以免附加到文件时它不起作用!
    猜你喜欢
    • 2014-07-22
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-24
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    相关资源
    最近更新 更多