1. Overview
In this article, we’ll check out some of the most common ways to delete the contents of a file. Whether we’re manipulating a text file, a CSV file, or a Kotlin file, we’re all faced with some file handling at some point.
2. The Standard IO Library
There are multiple ways to delete a file’s contents. We’ll use the standard library as it’s the most common way to achieve this.
2.1. Using the writeText() Function
Initially, we start with a reference to the file, which we assume is populated. From there, we can use the writeText() function to clear its contents:
val file = File("example.txt")
file.writeText("")
If we’re to check the contents of the file now, we’ll see that the file is empty. What this function does is override the contents of the file with an empty string, thus making it useful for straightforward operations.
2.2. Using FileWriter
While the writeText function is easy to use, there are scenarios where the FileWriter class might be more appropriate.
If we want to manipulate the file before deleting the contents we could use the write function with an empty string at the end of the code block:
val file = File("example.txt")
FileWriter(file).use {
/* ... */
it.write("")
}
In this case, though, because we’re using FileWriter, we have a bit more flexibility.
The file can be opened in truncate mode and if we don’t specify the append flag, the file length is set to zero, effectively deleting its contents. We’ll need to close the file afterward, as it may not be properly flushed or closed.
FileWriter(file).close()
This solution seamlessly integrates with existing Java code in mixed Kotlin/Java projects while giving us greater control and flexibility in the development process.
2.3. Using PrintWriter
We can use the PrintWriter class in the same way. PrintWriter extends the Writer class, thus giving us more control over the file.
Let’s have a look at the code example:
val file = File("example.txt")
PrintWriter(file).use {
/* ... */
it.write("")
}
PrintWriter(file).close()
In the first example, we use the file before writing an empty string. In the second one we open it in truncate mode and close it, therefore clearing its contents.
2.4. Using FileOutputStream
We’ve used FileWriter in the previous example, as it’s designed for writing streams of characters. Alternatively, for writing streams of raw bytes, a FileOutputStream would be a more suitable choice.
To clear the contents of a file with the FileOutputStream, we can again write an empty string after manipulating the file:
val file = File("example.txt")
FileOutputStream(file).use {
/* ... */
it.write("".toByteArray())
}
If we only want to remove the contents, we can open the stream and close it:
FileOutputStream(file).close()
2.5. Using BufferedWriter
The process of deleting contents with a BufferedWriter is similar to the previous methods. A BufferedWriter is commonly used to write to larger files by reducing the number of write operations, improving performance.
Let’s check out some examples by using the write function as well as opening and closing the stream:
val file = File("example.txt")
BufferedWriter(FileWriter(file)).use {
/* ... */
it.write("")
}
BufferedWriter(FileWriter(file)).close()
BufferedWriter takes an argument of type Writer, thus we can use a FileWriter or a PrintWriter.
2.6. Using RandomAccessFile
RandomAccessFile instances support both reading and writing to a random access file, which behaves like a large array of bytes stored in the file system.
Let’s use it to delete the contents of a file:
val file = File("example.txt")
RandomAccessFile(file, "rw").setLength(0)
We need to provide arguments for a file and the access mode. Once we set the length to 0, the files’ contents are cleared.
3. The NIO Library
Thus far, we’ve used the standard IO library. Let’s examine the NIO package for different file manipulation functions.
3.1. Using FileChannel
The first one we’re going to touch on is the FileChannel class. In particular, it provides a channel for reading, writing, mapping, and manipulating files with safe use by multiple concurrent threads. With that in mind, let’s have a look at how to delete content from a file:
FileChannel.open(Paths.get("example.txt"), StandardOpenOption.WRITE).truncate(0).close()
We use the open method with two arguments, one for the path to the file and another with the option on how the file is open, in this case in write mode. Subsequently, we truncate and close the file.
3.2. Using Files
Another class provided by the NIO package is the Files class. Let’s use the write method to clear the contents of a file:
Files.write(Paths.get("example.txt"), byteArrayOf(), StandardOpenOption.TRUNCATE_EXISTING)
With the write method, we pass the path to our file, specifically a byte array with the bytes to write and the options on how to open the file.
4. The Apache Commons IO
4.1. Using FileUtils
FileUtils is a powerful utility class provided by Apache Commons. In particular, it offers a wide range of helpful methods for working with files and directories in a simplified way.
We need to add the dependency to pom.xml:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.15.1</version>
</dependency>
With the dependency added, we can now start using the class:
FileUtils.write(file, "", Charset.defaultCharset())
5. Conclusion
In this article, we’ve illustrated the many options available for clearing file contents. Consequently, we can choose the method that best suits our needs.
As always, the full implementation of the code can be found over on GitHub.