Open In App

Read From Files using BufferedReader in Kotlin

Last Updated : 15 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In Kotlin, BufferedReader stores some characters as it reads into the buffer. This makes the reading faster and hence more efficient. In this article, we will understand how to use the BufferedReader to read the contents of a file. 

Note: To Read From Files using InputReader please refer to Read From Files using InputReader in Kotlin

Example

We can directly attach a BufferedReader to the file and read the contents of the whole file, as in the following code:

Kotlin




import java.do.File
import java.in.InputStream
  
fun main (args: Array<String>) {
  val inputString = File ("example.txt").bufferedReader ().use {
    it.readText () 
  }
  println (inputString)
}


We can also go line by line on the contents that we need so as to be able to process each line individually. In the following code, we go line by line and add a character at the beginning and the length of the string after the character:

Kotlin




import java.io.File
Import java.io.InputStream
  
fun main (args: Array<String>){
  val listOfLines = mutableListof<string> ()
  File ("example.txt").bufferedReader().useLines {
    lines->lines.forEach{
      var x = "> (" + it.length + ") " + it;
      listOfLines.add (x)
    }
  }
  listoflines.forEach{println(it)}
}


In the preceding code blocks, we are directly attaching the reader to the file. However, there are cases when we need to take a stream of data. In that scenario, we can get an Input Stream from the file that we want to read and then attach a BufferedReader to it. In the following code, we are trying to read line by line from the file input stream using a BufferedReader:

Kotlin




import java.io.File
import java.io.InputStream
  
fun main (args: Array<String>){
  val listofLines = mutableListof<String> ()
  val inputStream: InputStream = File ("example.txt").inputStream()
  inputStream.bufferedReader().useLines{
    lines -> lines.forEach {
      var x = "> (" + it.length + ") " + it;
      listOfLines.add(x)
    }
  }
  listofLines.forEach{ println(it) }
}


Here’s the output when we try to read all the contents of the file in one go:

Output:

GeeksforGeeks.org was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions.
The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction.
The content on GeeksforGeeks has been divided into various categories to make it easily accessible for the users.
Whether you want to learn algorithms, data structures or it is the programming language on it's own which interests you.
GeeksforGeeks has covered everything. 
Even if you are looking for Interview preparation material. 
GeeksforGeeks has a vast set of company-wise interview experiences to learn from.
that gives a user insights into the recruitment procedure of a company. 
Adding to this, it serves as a perfect platform for users to share their knowledge via contribute option.

The output resembles the file, ignoring the charset. We can also specify the desired charset, such as we do in the following code if needed:

bufferedReader (charset).use ( it.readText () }

When we go line by line using either of the preceding examples, we get the following output:

Output:

> (140) GeeksforGeeks.org was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions.
> (148) The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction.
> (113) The content on GeeksforGeeks has been divided into various categories to make it easily accessible for the users.
> (120) Whether you want to learn algorithms, data structures or it is the programming language on it's own which interests you.
> (37) GeeksforGeeks has covered everything. 
> (59) Even if you are looking for Interview preparation material. 
> (81) GeeksforGeeks has a vast set of company-wise interview experiences to learn from.
> (71) that gives a user insights into the recruitment procedure of a company. 
> (105) Adding to this, it serves as a perfect platform for users to share their knowledge via contribute option.

How does it work?

Using InputStream helps us get a stream of the file we wish to read. We can also read from the file directly though. In either case, the BufferedReader keeps preserving some data that it is reading in its buffer for faster operation, which increases the overall efficiency of the read operation, as compared to when using InputReader. We use the use() and/or useLines() method in place of Reader.readText() and so on so that it automatically closes the input stream at the end of execution, which is a much cleaner and more responsible way of handling I/O of files. However, if needed, one can use a method such as Reader.readText () when they want to handle opening and closing the stream on their own.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads