1. Introduction
In this tutorial, we are going to present several ways to read a file in Kotlin. Kotlin is a cross-platform, general-purpose programming language that is becoming more and more popular since it is now the preferred language for Android app developers.
Related Posts:
2. Create a file
First, let's create a file for testing frontbackend.txt
with the following content:
Tutorials:
- one
- two
- three
We can do it using the touch
command on Linux or with a Notepad on Windows. For a sake of simplicity let's put it into a folder with our sample Kotlin files.
3. Read a file using InputStream
3.1. Read all lines at once
Let's jump straight to the example code:
import java.io.File
import java.io.InputStream
fun main(args: Array<String>) {
val inputStream: InputStream = File("frontbackend.txt").inputStream()
val content = inputStream.bufferedReader().use { it.readText() }
println(content)
}
Here:
- first, we get and
InputStream
fromFile
object, inputStream.bufferedReader()
get aBufferedReader
responsible for reading streams,- finally, read the content with
use{ it.readTest() }
which is the same asCloseable.use(Reader.readText())
, - note that the last operation will automatically close the
InputStream
.
The output will be:
Tutorials:
- one
- two
- three
3.2. Read line by line
In the following example we make use of Reader.useLines(...)
method to read a file line by line:
import java.io.File
import java.io.InputStream
fun main(args: Array<String>) {
val inputStream: InputStream = File("frontbackend.txt").inputStream()
val out = mutableListOf<String>()
inputStream.bufferedReader().useLines { lines -> lines.forEach { out.add(it) } }
out.forEach { println(it) }
}
In this example:
- first, we read an
InputStream
of afrontbackend.txt
file, - next, we created a mutable list that will hold file lines,
- then, we read all lines and put them in our collection using the
bufferedReader().useLines
method, - finally, we printed all lines from our collection.
If everything is correct you should get the same result:
Tutorials:
- one
- two
- three
4. Conclusion
In this short article, we presented ways to read a file in Kotlin. The first method read all file content at once, second read line by line.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}