How can I delete the content of a file in Java?
Asked
Active
Viewed 1.5k times
6 Answers
14
How about this:
new RandomAccessFile(fileName).setLength(0);

Joachim Sauer
- 302,674
- 57
- 556
- 614

ZZ Coder
- 74,484
- 29
- 137
- 169
1
May problem is this leaves only the head I think and not the tail?
public static void truncateLogFile(String logFile) {
FileChannel outChan = null;
try {
outChan = new FileOutputStream(logFile, true).getChannel();
}
catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("Warning Logfile Not Found: " + logFile);
}
try {
outChan.truncate(50);
outChan.close();
}
catch (IOException e) {
e.printStackTrace();
System.out.println("Warning Logfile IO Exception: " + logFile);
}
}

MistereeDevlord
- 876
- 7
- 10
1
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();
}

Vlad Gudim
- 23,397
- 16
- 69
- 92
-
hi, thanks for reply.Is there any way to partially delete the file content means starting from particular offset and count to delete? – MGK Apr 12 '10 at 13:11
0
Open the file for writing, and save it. It delete the content of the file.

Axarydax
- 16,353
- 21
- 92
- 151
-1
try {
PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.flush();
writer.close();
}catch (Exception e)
{
}
This code will remove the current contents of 'file' and set the length of file to 0.

Alvi
- 767
- 8
- 20