Add text to end of a file in Kotlin
This post will discuss how to add text to the end of a file in Kotlin. The solution should append text to a file, not overwrite the existing data. If the file doesn’t exist, create it and write data.
There are numerous methods to add text at the end of a file in Kotlin:
1. Using Files.write() function
A simple and fairly efficient solution to call the Files.write() function to write text to a file with append mode since the default behavior of this function is to overwrite an existing file.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.io.IOException import java.nio.file.Files import java.nio.file.Paths import java.nio.file.StandardOpenOption fun main() { val path = Paths.get("/user/data/details.txt") val data = "..text to add.." try { Files.write(path, data.toByteArray(), StandardOpenOption.APPEND) println("Text appended to the file") } catch (e: IOException) { e.printStackTrace() } } |
The above solution does not create a new file if the target file doesn’t exist, but throws NoSuchFileException. To create a new file if the file doesn’t exist, we can pass the StandardOpenOption.CREATE option along with StandardOpenOption.APPEND.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.io.IOException import java.nio.file.Files import java.nio.file.Paths import java.nio.file.StandardOpenOption fun main() { val path = Paths.get("/user/data/details.txt") val data = "..text to add.." try { Files.write( path, data.toByteArray(), StandardOpenOption.APPEND, StandardOpenOption.CREATE ) println("Text appended to the file") } catch (e: IOException) { e.printStackTrace() } } |
2. Using FileWriter
Another alternative is to get a FileWriter instance and write streams of characters into a file using its write() function. To add text at the end of the file rather than the beginning, pass the boolean value true as the second parameter to the FileWriter constructor.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.io.FileWriter import java.io.IOException fun main() { val fileName = "/user/data/details.txt" val data = "..text to add.." try { FileWriter(fileName, true).use { it.write(data) println("Text appended to the file") } } catch (e: IOException) { e.printStackTrace() } } |
That’s all about adding text to the end of a file in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)