Reading from files using InputReader
Kotlin.io
provides a nice, clean API for reading from and writing to files. One way of doing this is by using InputReader
. We will see how to do that in this recipe.
Getting ready
You need to install a preferred development environment that compiles and runs Kotlin. You can also use the command line for this purpose, for which you need the Kotlin compiler installed along with JDK. You can also use IntelliJ IDEA for the development environment.
How to do it…
There are a lot of ways to go about reading from a file, but it is very important to understand the motivation behind them so as to be able to use the correct one for our purpose:
- First, we will try to get the
InputStream
of the file and use the reader to read the contents:
import java.io.File import java.io.InputStream fun main(args: Array<String>) { val inputStream: InputStream = File("lorem.txt").inputStream() val inputString = inputStream.reader().use { it.readText() } println(inputString...