Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting file contents android

I need to delete the contents of a file, before I write more information into it. I've tried different ways, such as where I delete the content but the file stays the same size, and when I start writing in it after the deletion, a blank hole appears to be the size of the deletion before my new data is written.

This is what I've tried...

BufferedWriter bw;
try {
    bw = new BufferedWriter(new FileWriter(path));
    bw.write("");
    bw.close();
}
catch (IOException e) {
    e.printStackTrace();
}

And I've also tried this...

File f = new File(file);
FileWriter fw;

try {
    fw = new FileWriter(f,false);
    fw.write("");
}
catch (IOException e) {
    e.printStackTrace();
} 

Can someone please help me with a solution to this problem.

like image 491
kassy Avatar asked Jun 18 '12 09:06

kassy


2 Answers

It might be because you are not closing the FileWriter, fw.close(); also you dont need to "delete" the old data, just start writing and it will overwrite the old data. So make sure you are closing everywhere.

This works for me:

    File f=new File(file);
    FileWriter fw;
    try {
        fw = new FileWriter(f);
        fw.write("");
       fw.close();
    } catch (IOException e) {
        e.printStackTrace();
    } 
like image 135
mbwasi Avatar answered Nov 02 '22 19:11

mbwasi


Try calling flush() before calling close().

FileWriter writer = null;

try {
   writer = ... // initialize a writer
   writer.write("");
   writer.flush(); // flush the stream
} catch (IOException e) {
   // do something with exception
} finally {
   if (writer != null) {
      writer.close();
   }
}
like image 25
Genzer Avatar answered Nov 02 '22 18:11

Genzer