Reading from files using BufferedReader
BufferedReader
stores some characters as it reads into the buffer. This makes the reading faster and hence more efficient. In this recipe, we will understand how to use the BufferedReader
to read the contents of a file.
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…
Follow the mentioned steps to learn more about the working of the BufferedReader
class:
- We can directly attach a
BufferedReader
to the file and read the contents of the whole file, as in the following code:
import java.io.File import java.io.InputStream fun main(args: Array<String>) { val inputString = File("lorem.txt").bufferedReader().use { it.readText() } println(inputString) }
- We can also go line by line on the contents that we need...