Skip to content
DeveloperMemos

Reading and Writing Files in Kotlin

Kotlin, Files1 min read

In many applications, it is necessary to read and write files for various purposes such as storing configuration data, caching results or persisting user-generated content. In this article, we will see how to read and write files in Kotlin.

Reading Files

To read a file in Kotlin, we can use the File class. The basic syntax for reading a file is:

1import java.io.File
2
3fun main() {
4 val fileName = "example.txt"
5 val file = File(fileName)
6
7 val lines = file.readLines()
8 for (line in lines) {
9 println(line)
10 }
11}

In this example, we first create a File object by passing the name of the file to be read. Then, we use the readLines() method to read all the lines in the file and store them in a list of strings. Finally, we iterate over the list and print each line to the console.

If we want to read the entire file as a single string, we can use the readText() method instead of readLines():

1val text = file.readText()
2println(text)

Writing Files

To write to a file in Kotlin, we can again use the File class. The basic syntax for writing to a file is:

1import java.io.File
2
3fun main() {
4 val fileName = "example.txt"
5 val file = File(fileName)
6
7 val text = "Hello, Kotlin!"
8 file.writeText(text)
9}

In this example, we first create a File object by passing the name of the file to be written. Then, we use the writeText() method to write the specified text to the file.

If we want to append to an existing file instead of overwriting it, we can use the appendText() method:

1val text = "Hello again, Kotlin!"
2file.appendText(text)

Conclusion

In this article, we learned how to read and write files in Kotlin using the File class. The readLines() and readText() methods are used for reading files, while the writeText() and appendText() methods are used for writing to files. With these basic operations, we can build more complex file handling functionalities for our applications.