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.

wattostudios
  • 8,666
  • 13
  • 43
  • 57
kassy
  • 51
  • 1
  • 2

3 Answers3

8
FileWriter (path, false)

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

mbwasi
  • 3,612
  • 3
  • 30
  • 36
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();
   }
}
Genzer
  • 2,921
  • 2
  • 25
  • 38
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();
    } 
mbwasi
  • 3,612
  • 3
  • 30
  • 36