Read From Files using BufferedReader in Kotlin
Last Updated :
15 Mar, 2022
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.
Similar Reads
Read From Files using InputReader in Kotlin
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 wa
5 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
Play Audio From URL in Android using Kotlin
Many applications want to add different types of audio files to their android applications. These audio files are played using a media player within the android application. We can play audio files within the android application from different sources by playing audio from a web URL or by simply add
4 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
Code Formatting in Kotlin using ktlint
As we all know about the kotlin language which is recommended by google particularly for android app development, and of course, it made the life of android app developers easier. But if you are a beginner in this field then you may not know that you need to write the codes in the desired format. an
4 min read
Android Exoplayer using Kotlin
ExoPlayer View is one of the most used UI components in media streaming applications for displaying video files within android applications. It is similar to that of Video View, but the quality of the video player in Exoplayer compared to video view is better. In this article, we will look at How to
3 min read
Implement Instant Search Using Kotlin Flow Operators
A flow is a type in coroutines that can emit multiple values sequentially, as opposed to suspend functions, which only return a single value. A flow, for example, can be used to receive real-time updates from a database. Flows are constructed on top of coroutines and can return multiple values. A fl
4 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 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
Kotlin Flow in Android with Example
Kotlin Flow is one of the latest addition to the Kotlin Coroutines. With Kotlin Flow we can handle streams of data asynchronously which is being executed sequentially. What are we going to build in this article? We will build a simple app that fetches some data from API and shows it on the screen.
8 min read