how to read file using kotlin

How to Read a File in Kotlin

In this article we will look about how to read a file in Kotlin Programming language, whether it is a text file, or a raw json file, from assets folder of our Android Studio Project.

What we are going to achieve:

Our intention in this article is simple, to fetch a local json file into a string using Kotlin Programming Language and use it according to our need.

Good old days using Java:

Let us recap how we used to read a file using Java.

Here is the code snippet used to read the contents of a file using Java Programming Language:

How to achieve this in Kotlin?

Let us see how to achieve the same using Kotlin Programming Language. Here is the code snippet to perform the same in Kotlin:

So, Whats so Special in Kotlin ? Is there a simple way to achive the same differently and in a simple way?

The Answer is Yes, we can do so by means of available extension functions, a Powerful feature in Kotlin.

Read File in a simplified way using Extension Function

In the above code snippet, bufferedReader() is an extension function in Kotlin IO package which can be readily used to achieve the same as the above Java code snippet.

Related Posts