Read a Text File from Resources in Kotlin



In this article, we will see how we can read a text file using Kotlin library functions. Kotlin is based on Java, hence we can use different Java library functions in Kotlin too.

Example - BufferedReader

Go ahead and create a Kotlin file in your workspace and name it " ReadFile.kt". Keep a text file with some data in the same directory. For this example, our Text file looks like this −

Welcome to the best tutorial website - www.tutorialsPoint.com
This is the Text file that we want to read via Kotlin

Execute the following piece of code to read the above text file.

// importing java library function
// to read files from different sources
import java.io.File
import java.io.BufferedReader

fun main(args: Array<String>) {
   val bufferedReader: BufferedReader = File("Text.txt").bufferedReader()
   val inputString = bufferedReader.use { it.readText() }
   println(inputString)
}

Output

The above program will read the text file in the same directory and give us the following output

Running] cd "<<Your workspace>>" && kotlinc readFile.kt
-include-runtime -d readFile.jar && java -jar readFile.jar
Welcome to the best tutorial website - www.tutorialsPoint.com
This is the Text file that we want to read via Kotlin

Example - InputStream

File information can be read using another library function, that is, InputStream. In the following example, we will read the same text file using InputStream.

import java.io.File
import java.io.InputStream
fun main(args: Array<String>) {
   val inputStream: InputStream = File("Text.txt").inputStream()
   val inputString = inputStream.bufferedReader().use { it.readText() }
   println(inputString)
}

Output

It will produce the following output

[Running] cd "<<Your workspace>>" && kotlinc readFile.kt
-include-runtime -d readFile.jar && java -jar readFile.jar
Welcome to the best tutorial website - www.tutorialsPoint.com
This is the Text file that we want to read via Kotlin
Updated on: 2021-11-23T07:18:26+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements