Delete android file contents

I need to delete the contents of the file before writing additional information. I tried different ways, for example, when I delete the contents, but the file remains the same size, and when I start writing in it after the deletion, the empty hole looks like the size of the deletion before my new data is written.

Here is what I tried ...

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

And I 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.

+5
source share
3 answers
FileWriter (path, false)

A lie tells the author to trim the file instead of adding to it.

+9
source

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();
   }
}
0
source

, , FileWriter, fw.close(); "" , . , .

:

    File f=new File(file);
    FileWriter fw;
    try {
        fw = new FileWriter(f);
        fw.write("");
       fw.close();
    } catch (IOException e) {
        e.printStackTrace();
    } 
0
source

All Articles