Android - 应用关闭时保留文件

时间:2010-06-14 16:13:47

标签: java android file outputstream bufferedwriter

我正在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。

1 个答案:

答案 0 :(得分:1)

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

相关问题