Skip to content Skip to sidebar Skip to footer

Clearing File Content In Internal Storage On Android

I have a logging class for writing into a file in the app's internal storage space. Whenever the log file exceeds the size limit. For clearing the contents, I am closing the curren

Solution 1:

You could also overwrite your file with nothing.

UPDATE:

There seems to be a better option with getFilesDir () Have a look at this question How to delete internal storage file in android?


Solution 2:

Write empty data into file:

String string1 = "";
        FileOutputStream fos ;
        try {
            fos = new FileOutputStream("/sdcard/filename.txt", false);
            FileWriter fWriter;

            try {
                fWriter = new FileWriter(fos.getFD());

                fWriter.write(string1);
                fWriter.flush();
                fWriter.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                fos.getFD().sync();
                fos.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

In this code:

fos = new FileOutputStream("/sdcard/filename.txt", false);

FALSE - for write new content. If TRUE - text append to existing file.


Solution 3:

public void writetofile(String text){ // text is a string to be saved    
   try {                               
        FileOutputStream fileout=openFileOutput("mytextfile.txt", false); //false will set the append mode to false         
        OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);  
        outputWriter.write(text);  
        outputWriter.close();  
        readfromfile();  
        Toast.makeText(getApplicationContext(), "file saved successfully",  
                Toast.LENGTH_LONG).show();  
        }catch (Exception e) {  
            e.printStackTrace();  
    }  
}

Post a Comment for "Clearing File Content In Internal Storage On Android"