Read From Files using InputReader in Kotlin
Last Updated :
13 Mar, 2022
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.
Similar Reads
Read From Files using BufferedReader in Kotlin 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 Fro
4 min read
Generate PDF File in Android using Kotlin Most of the applications provide users with the facility of bills to be downloaded from the mobile applications. This type of application gets the data from the APIS or data within the application and this data is used to generate the PDF files. PDF files within android are generated using canvas. I
7 min read
Load PDF From URL in Android with Kotlin PDF View is most of the applications to display the PDF files within the application to display the pdf within our own application rather than redirecting to another application. If we want to display multiple pdf files within our application we have to host these files and then access these files w
4 min read
How to Read a File using Applet? In this article, we will learn how to read the content of the file using Java and display those contents using Applet. Approach UsedThe user should type the name of the file in the input field that asks for the filename in the output applet window. If the file is already present, it will display the
2 min read
XML Parsing in Android using DOM Parser Android DOM(Document Object Model) parser is a program that parses an XML document and extracts the required information from it. This parser uses an object-based approach for creating and parsing the XML files. In General, a DOM parser loads the XML file into the Android memory to parse the XML doc
6 min read
XML Parsing in Android using SAX Parser Generally, XML (Extensible Mark-up Language) is a commonly used data exchange format to interchange servers' data. In Android, SAX stands for Simple API for XML and is a widely used API for XML parsing. Like the DOM parser, the SAX parser is also used to perform in-memory operations to parse the XML
6 min read
use Keyword in Kotlin with Example Kotlin is a statically typed, general-purpose programming language developed by JetBrains, that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011 and is a new language for the JVM. Kotlin is an object-oriented language, and a âbetter
3 min read
How to Read File Word By Word in Golang? File reading is such an important aspect of a programming language. We need to perform certain operations programmatically, using automation in file reading/writing allows us to create certain programs/projects which might have looked impossible otherwise. File InputTo work with files, we have to in
5 min read
Implement Universal Image Loader Library in Android using Kotlin Universal Image Loader library is also referred to as (UIL). It is similar to Picasso and Glide which is used to load the images from the URL within our image view inside our android application. This image loading library has been created to provide a powerful, flexible, and customizable solution t
4 min read
How to Read Data From SQLite Database in Android using Jetpack Compose? In the 1st part of our SQLite database, we have seen How to Create and Add Data to SQLite Database in Android using Jetpack Compose. In that article, we have added data to our SQLite Database. In this article, we will read all this data from the SQLite database and display this data in our ListView
8 min read