Android - save file when application closes

I create a file in my android application as follows:


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.....");
    }
}

And I write to the file during application startup as follows:


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();
}

This works fine, but when my application closes, the file is deleted, and when the application starts again, all the information I wrote to it was gone.

How can I make sure the file is saved even after the application is closed?

Update:

I changed MODE_PRIVATE to MODE_APPEND and the problem is fixed, thanks Skirmish.

+3
source share

Source: https://habr.com/ru/post/1749964/


All Articles