English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin program appends text to an existing file

Kotlin Examples in Full

In this program, you will learn different methods to append text to existing files in Kotlin.

Before appending text to an existing file, we assume that insrcThere is a folder namedtest.txtfile.

This istest.txtcontent

This is a
Test file.

Example1:Append text to an existing file

import java.io.IOException
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.StandardOpenOption
fun main(args: Array<String>) {
    val path = System.getProperty("user.dir") + "\\src\\test.txt"
    val text = "Added text"
    try {
        Files.write(Paths.get(path), text.toByteArray(), StandardOpenOption.APPEND)
    } catch (e: IOException) {
    }
}

When running the program,test.txtThe file now contains:

This is a
Test file.Added text

In the above program, we use the System's user.dir property to get the current directory stored in the variable path. SeeKotlin program to get the current directoryMore information.

Similarly, the text to be added is also stored in the variable text. Then, in a try-In the catch block, we use the Files' write() method to append text to an existing file.

The write() method takes the given file path, the text to be written, and how to open the file for writing. In our example, we use the APPEND option for writing.

Since the write() method may return IOException, we use a try-to correctly catch exceptions.

Example2:Use FileWriter to append text to an existing file

import java.io.FileWriter
import java.io.IOException
fun main(args: Array<String>) {
    val path = System.getProperty("user.dir") + "\\src\\test.txt"
    val text = "Added text"
    try {
        val fw = FileWriter(path, true)
        fw.write(text)
        fw.close()
    } catch (e: IOException) {
    }
}

The output of the program is the same as the example1Same.

In the above program, instead of using the write() method, we use an instance (object) of FileWriter to append text to an existing file.

When creating the FileWriter object, we pass the file path and true as the second parameter. true indicates that the file can be appended.

Then, we use the write() method to append the given text and close the file writer.

This is the equivalent Java code:Java Program to Append Text to Existing File.

Kotlin Examples in Full