0

I have this web browser app where I store the browsing history in a .txt file in the user's SD Card. The way I clear the history is just deleting the file, and I throw an exception if the History is cleared again if the file doesn't exist (This exception is temporary, as I plan to delete it in the future, but is in there for testing purposes). Is there a way to clear the history.txt without deleting the file that is cleaner? Here's the code snippet of how I go about "clearing" the file:

 if(MainActivity.file.exists()){
        MainActivity.file.delete();
        for(int x = 0; x < 1000; x++){
            urls[x] = "";
        }
        adap.notifyDataSetChanged();}
else if(!MainActivity.file.exists()){
        throw new InvalidFileDeletionException("File does not exist and therefore can not be deleted.");
    }
Nicholas Eason
  • 290
  • 4
  • 13

2 Answers2

1

you could do like on this post : rewrite the content with blank ("") :

(I'll copy the original post here : )

To overwrite file foo.log:

File myFoo = new File("path/to/history.txt");
FileOutputStream fooStream = new FileOutputStream(myFoo, false); // true to append
                                                                 // false to overwrite.
byte[] myBytes = "".getBytes() 
fooStream.write(myBytes);
fooStream.close();

or

File myFoo = new File("path/to/history.txt");
FileWriter fooWriter = new FileWriter(myFoo, false); // true to append
                                                     // false to overwrite.
fooWriter.write("");
fooWriter.close();
Community
  • 1
  • 1
Rocel
  • 1,029
  • 1
  • 7
  • 22
0

Try this:

FileWriter fw = new FileWriter(path + "/history.txt", false);
fw.close();

Of course, there are neater ways of handling the path and filename but you get the picture.

Simon
  • 14,407
  • 8
  • 46
  • 61