How to read a file with Kotlin?

3

I have a .txt file with some information I would like to read to a string through Kotlin.

I am a beginner in the language and would like to know how to read a file with Kotlin.

    
asked by anonymous 08.08.2017 / 16:12

2 answers

5

Most of Kotlin's library is the same as Java's, one of the trumps of the language has already been born with all that library available.

You can read the entire file and then manipulate it, read lines , or read the way you think better , or read by streams . All documentation of what you can do from the most varied forms.

At last it depends on the need. Examples .

Stream

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

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

    val inputString = inputStream.bufferedReader().use { it.readText() }
    println(inputString)
}

Line by line

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

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

    inputStream.bufferedReader().useLines { lines -> lines.forEach { lineList.add(it)} }
    lineList.forEach{println(">  " + it)}
}

BufferedReader

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

fun main(args: Array<String>) {
    val bufferedReader: BufferedReader = File("kotlination.txt").bufferedReader()

    val inputString = bufferedReader.use { it.readText() }
    println(inputString)
}

Line by line

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

fun main(args: Array<String>) {
    val bufferedReader = File("kotlination.txt").bufferedReader()
    val lineList = mutableListOf<String>()

    bufferedReader.useLines { lines -> lines.forEach { lineList.add(it) } }
    lineList.forEach { println(">  " + it) }
}
    
08.08.2017 / 16:23
3

(Almost) equal to Java

You can use the Java libraries for this. In fact, not only that, a lot of Kotlin's library is Java's.

Obviously there are several ways to work with files. A simple example of how to read all the lines of a .txt file is:

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

fun main(args: Array<String>) {
    val stream: InputStream = File("wallace.txt").inputStream()

    val str = stream.bufferedReader().use { it.readText() }
    println(str)
}

Or, read line by line

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

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

    stream.bufferedReader().useLines { l -> l.forEach { linhas.add(it)} }

    linhas .forEach { println(">  " + it) }
}

Obs : Note that it is the default (implicit) parameter name of an anonymous function.

I've taken the examples from Kotlination.

    
08.08.2017 / 16:22