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

1. Using PrintWriter

The recommended solution is to create a PrintWriter instance, which results in the specified file being truncated to size zero. Note that if the file doesn’t exist, a new file will be created.

This is demonstrated below with the use function, which automatically takes care of closing the stream:

Download Code

2. Using BufferedWriter

Another option is to create a BufferedWriter using Files.newBufferedWriter(…) and specify the StandardOpenOption.TRUNCATE_EXISTING option to truncate the file to length 0 (if it exists). Its usage is demonstrated below with the use function:

Download Code

3. Using FileChannel

The FileChannel class contains the truncate() function to truncate a file to the specified size. It can be used as follows:

Download Code

 
Alternately, you can directly specify the StandardOpenOption.TRUNCATE_EXISTING option to the open() function, which results in the file being truncated to a size of 0 (if it exists).

Download Code

4. Using RandomAccessFile

The RandomAccessFile class provides support for setting the length of a file using the setLength() function. To truncate a file, you can open the file in rw mode and pass the length as 0 to the setLength() function:

Download Code

5. Using FileOutputStream

The following solution constructs a FileOutputStream instance with append mode as false, which truncates the file to length 0. Here’s how code would look like:

Download Code

6. Using FileWriter

Finally, you can also create a FileWriter object which would truncate the file if it already exists. This is demonstrated below:

Download Code

That’s all about truncating a file in Kotlin.