Open In App

Read From Files using InputReader in Kotlin

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

Basically, kotlin.io provides a nice, clean API for reading from and writing to files. In this article, we are going to discuss how to read from files using inputReader in Kotlin. One way of doing this is by using inputreader. We will see how to do that in this article.

Example

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 Input Stream of the file and use the reader to read the contents:

Kotlin




import java. io. File
import java . io. InputStream
fun main (args: Array<String>) {
  val inputStream: InputStream = File ("gfg.txt").inputStream()
  val inputString = inputStream.reader().use {it.readText()}
  println (inputString)
}


In the preceding code block, gfg.txt is simply a file that we want to read. The file is located in the same folder as our code source file. If we need to read a file located in a different folder, it looks similar to the following:

File ("/path/to/file/gfg.txt")

This piece of code simply takes all the text in the file and prints it on the console. Another way of reading file contents is by directly creating a reader of the file as we do in this code:

Kotlin




import java.io.File
fun main (args: Array<String>) {
  val inputString = File("gfg.txt").reader().use{it.readText()}
  println (inputString)
}


The output of both preceding code blocks will simply be the text in the file as it is. In our case, it was as follows:

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.

Now, what if we want to read the file line by line because we want to do some processing on each line? In that case, we use the useLines( ) method in place of use(). Check out the following example, where we get an input stream from the file and use the useLines () method to get each line one after the other:

Kotlin




import java.io.File
import java.io.InputStream
  
fun main (args: Array<String>) {
  val listOfLines = mutableListof<String> ()
  val inputStream: InputStream = File ("gfg.txt").inputStream()
  inputStream.reader().useLines { lines -> lines.forEach {
    listOfLines.add (it) 
  }
    listOfLines.forEach{println("$ "+ it )} 
 }


Alternatively, if we wish to use a reader directly on the file, we do this:

Kotlin




import java.io.File
fun main (args: Array<String>){
  val listOfLines = mutableListOf<String>()
    
  File ("gfg.txt").reader().useLines{ lines ->lines.forEach {
    listOfLines.add (it) }
  }
  listOfLines.forEach{println("$ " + it}
}


The output, in this case, will be the following:

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.

Did you note that we used the use() and useLines() methods for reading the file? The call to the Closeable. use () function will automatically close the input at the end of the lambda’s execution. Now, we can of course use Reader.readText (), but that does not close the stream after execution. There are other methods apart from use(), such as Reader.readText(), and so on, that can be used to read the contents of a stream or file. The decision to use any method is based on whether we want the stream to be closed on its own after execution, or we want to handle closing the resources, and whether or not we want to read from a stream or directly from the file.

BufferedReader reads a couple of characters at a time from the input stream and stores them in the buffer. That’s why it is called BufferedReader. On the other hand, Input Reader reads only one character from the input stream and the remaining characters still remain in the stream. There is no buffer in this case. This is why BufferedReader is fast, as it maintains a buffer, and retrieving data from the buffer is always quicker compared to retrieving data from disk.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads