How to Read a File in Kotlin

0
1376
how to read file using 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:

BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("news_data_file.json"), "UTF-8"));
// do reading, usually loop until end of file reading
String mLine;
while ((mLine = reader.readLine()) != null) {
//process line
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}

view raw
ReadFile.java
hosted with ❤ by GitHub

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:

try {
val inputStream:InputStream = assets.open("news_data_file.json")
val inputStreamReader = InputStreamReader(inputStream)
val sb = StringBuilder()
var line: String?
val br = BufferedReader(inputStreamReader)
line = br.readLine()
while (br.readLine() != null) {
sb.append(line)
line = br.readLine()
}
br.close()
Log.d(TAG,sb.toString())
} catch (e:Exception){
Log.d(TAG, e.toString())
}

view raw
ReadFile.kt
hosted with ❤ by GitHub

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

try {
val inputStream:InputStream = assets.open("news_data_file.json")
val inputString = inputStream.bufferedReader().use{it.readText()}
Log.d(TAG,inputString)
} catch (e:Exception){
Log.d(TAG, e.toString())
}

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.

0 0 vote
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments