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.
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.
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 .
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)
}
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)}
}
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)
}
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) }
}
(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.