tags:

views:

134

answers:

3

hi, May i please know how can i delete the content of the file in java? Thanks in advance.

+1  A: 

Open the file for writing, and save it. It delete the content of the file.

Axarydax
Did you mean, "Open the file for writing, and _close_ it"?
Marcelo Cantos
+7  A: 

How about this:

new RandomAccessFile(fileName).setLength(0);
ZZ Coder
A: 

You could do this by opening the file for writing and then truncating its content, the following example uses NIO:

import static java.nio.file.StandardOpenOption.*;

Path file = ...;

OutputStream out = null;
try {
    out = new BufferedOutputStream(file.newOutputStream(TRUNCATE_EXISTING));
} catch (IOException x) {
    System.err.println(x);
} finally {
    if (out != null) {
        out.flush();
        out.close();
    }
}

Another way: truncate just the last 20 bytes of the file:

import java.io.RandomAccessFile;


RandomAccessFile file  = null; 
try { 
    file = new RandomAccessFile ("filename.ext","rw");
    // truncate 20 last bytes of filename.ext 
    file.setLength(file.length()-20); 
} catch (IOException x) { 
    System.err.println(x); 
} finally { 
    if (file != null) file.close(); 
} 
Totophil
hi, thanks for reply.Is there any way to partially delete the file content means starting from particular offset and count to delete?
Santhosh