Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read plain text file in kotlin?

There may be various way to read plain text file in kotlin.

I want know what are the possible ways and how I can use them.

like image 812
Anisuzzaman Babla Avatar asked Mar 15 '19 12:03

Anisuzzaman Babla


People also ask

How do you read lines in Kotlin?

To read a line of string in Kotlin, you can use readline() function.

How do I get a file from Kotlin?

Get File Extension in Kotlin Kotlin – Get File Extension : In Kotlin, to extract or get the file extension, use File. extension property. File. extension is a String value.

What is BufferedReader in Kotlin?

BufferedReader(in: Reader!, sz: Int) Creates a buffering character-input stream that uses an input buffer of the specified size. BufferedReader(in: Reader!) Creates a buffering character-input stream that uses a default-sized input buffer.


Video Answer


2 Answers

1. Using BufferedReader

    import java.io.File
    import java.io.BufferedReader

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

2. Using InputStream

Read By Line

    import java.io.File
    import java.io.InputStream

    fun main(args: Array<String>) {
        val inputStream: InputStream = File("example.txt").inputStream()
        val lineList = mutableListOf<String>()

        inputStream.bufferedReader().forEachLine { lineList.add(it) } 
        lineList.forEach{println(">  " + it)}
    }

Read All Lines

    import java.io.File
    import java.io.InputStream

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

3. Use File directly

    import java.io.File
    import java.io.BufferedReader

    fun main(args: Array<String>) {
        val lineList = mutableListOf<String>()

        File("example.txt").useLines { lines -> lines.forEach { lineList.add(it) }}
        lineList.forEach { println(">  " + it) }
    }
like image 181
Anisuzzaman Babla Avatar answered Oct 06 '22 20:10

Anisuzzaman Babla


I think the simplest way to code is using kotlin.text and java.io.File

import java.io.File

fun main(args: Array<String>) {
    val text = File("sample.txt").readText()
    println(text)
}
like image 34
katsusuke Avatar answered Oct 06 '22 18:10

katsusuke