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 development.
Related Posts:
2. Create a file
First, let's create a file for testing purposes with a name frontbackend.txt
and the following content:
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
The first approach use BufferedReader
and use
method:
Here:
- first, we get an
InputStream
fromFile
object, - next, using
inputStream.bufferedReader()
we get aBufferedReader
responsible for reading streams, - finally, to read the content we use the
use{ it.readTest() }
command which is the same asCloseable.use(Reader.readText())
in Java, - note that the last operation will automatically close the
InputStream
.
The output will be:
3.2. Read line by line
In the following example we make use of Reader.useLines(...)
method to read a file line by line:
In this example:
- first, we read an
InputStream
of afrontbackend.txt
file, - next, we created a mutable list that will hold file content lines,
- then, we read all lines and put them in our collection using the
bufferedReader().useLines
method, - the final step is to print all lines from our collection.
If everything is correct you should get the same result as in the first approach:
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 }}