This post will discuss how to truncate a file to size zero in Java.

There are several ways to truncate a file to size zero before writing in plain Java and using third-party libraries. These are discussed below in detail:

1. Using PrintWriter

We can create a new PrintWriter instance with the specified file. If the file exists, it will be truncated to size zero; otherwise, a new file will be created.

Download Code

2. Using Files Class

With Java 7, we can use Files.newBufferedWriter(…), which returns a BufferedWriter. It opens the file for writing, creating the file if it doesn’t exist, or initially truncating an existing regular-file to a size of 0 if it exists.

Download Code

3. Using FileOutputStream

We can also construct a FileOutputStream with the specified file. If the file exists, then it will be truncated to size 0.

Download Code

4. Using FileWriter

We can also construct a FileWriter object with the given File object. If the file already exists, then the file will be truncated before writing.

Download Code

5. Using FileChannel

FileWriter is a channel for reading, writing, mapping, and manipulating a file. We can use its open() method to open a file. If the StandardOpenOption.TRUNCATE_EXISTING option is specified, the file will be truncated to a size of 0 if it exists.

Download Code

 
If StandardOpenOption.TRUNCATE_EXISTING option is not provided, we can call its truncate() method to truncate this channel’s file to the size 0.

Download Code

6. Using RandomAccessFile

A RandomAccessFile instance supports both reading and writing to a random access file. We can call its setLength() method to set the desired length of this file. To truncate the file, pass 0 as an argument to this method.

Download Code

7. Using Guava Library

Guava’s Files.asCharSink(File, Charset, FileWriteMode) method can be used for writing text data to the given file. When no mode is provided, the file will be truncated before writing, or a new file is created when the target file doesn’t exist.

Download Code

8. Using Apache Commons IO

FileUtils class from Apache Commons IO library has the writeStringToFile(File, String, Charset) method, which writes a string to a file. If the file already exists, then the file will be truncated before writing.

Download Code

That’s all about truncating a file in Java.

 
Also See:

Write to a file in Java

Append text to a file in Java