This post will discuss how to delete the contents of a file without deleting the file itself in Java.

1. Using BufferedWriter

A simple solution is to get a BufferedWriter with the Files.newBufferedWriter(…) method with the TRUNCATE_EXISTING standard open option. It truncates the file to length 0 if it already exists (when opened for writing).

The complete usage is demonstrated below using try-with-resource statement (Java 7+), which automatically take care of closing the opened streams and channels:

Download Code

2. Using PrintWriter

Alternatively, you can create a new PrintWriter with the specified file name. It results in a file truncated to size zero if it already exists.

Download Code

 
Here’s an equivalent version with try-with-resource statement, which take care of closing the stream:

Download Code

3. Using FileChannel

The FileChannel class provides the truncate() method that can truncate a file to the given size. Its usage is demonstrated below:

Download Code

4. Using RandomAccessFile

With the RandomAccessFile class, you can set the length of a file using the setLength() method. To truncate the file, pass the length of the file as 0, as shown below:

Download Code

5. Using FileOutputStream

Finally, you can use FileOutputStream to truncate a file to length 0 if it exists. A typical invocation for this class would look like:

Download Code

That’s all about deleting the contents of a file without deleting the file itself in Java.