Signup/Sign In

Kotlin File Handling

In this tutorial we will discuss about basics of file handling in Kotlin. Files are used to persist data in memory as after execution of program the data is lost if it is not stored.

There are many ways to create a file, read and write in a file. We'll discuss some of them briefly.

Kotlin Create a file

Generally in many write methods a file is created itself but we'll see a method to create a file. We'll use File class available in java.io package. The constructor takes file name as the argument. We'll use createNewFile() method to create a file.

If a file with given filename does not exists, createNewFile() method will create a new file and returns true. If a file with filename already exits, it will return false:

import java.io.File

fun main() {
    val fileName = "Demo.txt"
    // Create file object
    val file = File(fileName)
    // Create file
    var isCreated = file.createNewFile()
    if (isCreated)
        println("File is created")
    else
        println("File is not created")
    // Again create file
    isCreated = file.createNewFile()
    if (isCreated)
        println("File is created")
    else
        println("File is not created")
}


File is created
File is not created

We can also check existence of file using file.exists() method

Kotlin Writing to a File

We can write data in a file using writeText() method.

  • It will take String as an argument and writes it into the file.

  • It will create a new file if no file exists with specified name.

  • If file already exists, it will replace the file.

  • The given data is first encoded using UTF-8 charset by default. We can also specify any other charset.

import java.io.File

fun main() {
    val fileName = "Demo.txt"
    
    val file = File(fileName)
    file.writeText("Hello World")
    file.writeText("Bye world")
}

If we check the Demo.txt file we will see only Bye world in it. It is because writeText() will replace all the content present in file. If we wants to prevent the present data from getting lost, we can use appendText() function instead of writeText() function.

Kotlin Read from a file

For reading content line by line we can use forEachLine() method. It will read data line by line from the file.

import java.io.File

fun main() {
    val fileName = "Demo.txt"
    val file = File(fileName)
    file.forEachLine {
        println(it)
    }
}

We can also use readText() function to read data from a file:

import java.io.File

fun main() {
    val fileName = "Demo.txt"
    val file = File(fileName)
    val data = file.readText()
    println(data)
}

Summary

In this tutorial we discussed basic methods of creating a file, reading data from it and writing data to it.



About the author:
I'm a writer at studytonight.com.