Deleting file contents android
Asked Answered
H

3

5

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.

Hube answered 18/6, 2012 at 9:51 Comment(2)
Can't you just delete the file and create a new empty one?Seafood
No, I need to be the same file but thanks for your answerHube
U
8
FileWriter (path, false)

The false will tell the writer to truncate the file instead of appending to it.

Unhurried answered 18/6, 2012 at 11:14 Comment(2)
Yes, that's what I want because I want to clear the contents of the file.Hube
Sorry, didnt see the false in the second piece of code there.Unhurried
J
1

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();
   }
}
Jespersen answered 18/6, 2012 at 10:1 Comment(1)
I tried but it still is the same. I do not understand. Thank you for your answerHube
U
1

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();
    } 
Unhurried answered 18/6, 2012 at 15:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.