filekotlintext-filesbufferedreader

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.


Solution

  • 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) }
        }