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
2010-04-12 13:03:56
Did you mean, "Open the file for writing, and _close_ it"?
Marcelo Cantos
2010-04-12 13:05:31
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
2010-04-12 13:06:54
hi, thanks for reply.Is there any way to partially delete the file content means starting from particular offset and count to delete?
Santhosh
2010-04-12 13:11:34