How to read File in Kotlin

In this tutorial, I will show you how to read File in Kotlin using InputStream or BufferedReader or File directly.

Related Posts:
Kotlin Android – Read JSON file from assets using Gson
Ways to write to File in Kotlin

Create the file

First, we need a file to read. So create a file named bezkoder.txt with following content:

bezkoder.com
-> Programming Tutorial
-> Becoming zKoder
-> Master Programming

Because we don’t indicate path for bezkoder.txt file, so you should put it in the root folder of the Project (the folder src is located in).

If you wanna read file in resources folder \app\src\main\res\, just change the path:
File("bezkoder.txt") -> File("src/main/res/bezkoder.txt")

Kotlin read File using InputStream

Read all lines

Steps to do:

  • retrieve InputStream from File, then get BufferedReader using bufferedReader() method
  • use Closeable.use() method along with Reader.readText() method inside block.
    Closeable.use(Reader.readText())
    

Note:
Reader implements Closeable
Closeable.use() will automatically close the input at the end of the lambda’s execution

Practice:

import java.io.File
import java.io.InputStream

fun main(args: Array<String>) {
  val inputStream: InputStream = File("bezkoder.txt").inputStream()

  val inputString = inputStream.bufferedReader().use { it.readText() }
  println(inputString)
}

Output:

bezkoder.com
-> Programming Tutorial
-> Becoming zKoder
-> Master Programming

Read line by line

Steps to do:

  • retrieve InputStream from File, then get BufferedReader using bufferedReader() method
  • use Reader.useLines() method with Kotlin Sequence (a sequence of all the lines) inside block. It will automatically close the reader once the processing is complete
    Reader.useLines(block: Sequence)
    

Practice:

import java.io.File
import java.io.InputStream

fun main(args: Array<String>) {
  val inputStream: InputStream = File("bezkoder.txt").inputStream()
  val lineList = mutableListOf<String>()

  inputStream.bufferedReader().useLines { lines -> lines.forEach { lineList.add(it)} }
  lineList.forEach{println(">  " + it)}
}

Output:

> bezkoder.com
>  -> Programming Tutorial
>  -> Becoming zKoder
>  -> Master Programming

Kotlin read File using BufferedReader

Read all lines

Steps to do:

  • create BufferedReader from File
  • use BufferedReader.use() method along with Reader.readText() method inside block.
    BufferedReader.use(Reader.readText())
    

Practice:

import java.io.File
import java.io.BufferedReader

fun main(args: Array<String>) {
  val bufferedReader: BufferedReader = File("bezkoder.txt").bufferedReader()

  val inputString = bufferedReader.use { it.readText() }
  println(inputString)
}

Output:

bezkoder.com
-> Programming Tutorial
-> Becoming zKoder
-> Master Programming

Read line by line

Steps to do:

  • create BufferedReader from File
  • use Reader.useLines() method that will automatically close the reader once the processing is complete
    Reader.useLines(block: Sequence)
    

Practice:

import java.io.File
import java.io.BufferedReader

fun main(args: Array<String>) {
  val bufferedReader = File("bezkoder.txt").bufferedReader()
  val lineList = mutableListOf<String>()

  bufferedReader.useLines { lines -> lines.forEach { lineList.add(it) } }
  lineList.forEach { println(">  " + it) }
}

Output:

>  bezkoder.com
>  -> Programming Tutorial
>  -> Becoming zKoder
>  -> Master Programming

Kotlin read File directly

There are two ways to read all lines of a file using File directly:

  • File.useLines() method along with Kotlin Sequence
  • File.readLines() method to return a List<String>
import java.io.File
import java.io.BufferedReader

fun main(args: Array<String>) {
  val lineList = mutableListOf<String>()

  File("bezkoder.txt").useLines { lines -> lines.forEach { lineList.add(it) }}
  lineList.forEach { println(">  " + it) }

//  val lineList = File("bezkoder.txt").readLines()
//  lineList.forEach { println(">  " + it) }
}

Output:

>  bezkoder.com
>  -> Programming Tutorial
>  -> Becoming zKoder
>  -> Master Programming

Conclusion

Today we’ve learned many ways to use Kotlin to read a File line-by-line or all lines. Now you can use InputStream or BufferedReader or File directly to do the work.

Happy Learning! See you again.

Further Reading

Vue 3 Composition API tutorial with examples

Vue introduces Composition API (Function-based API) as an addition to current Options-based API. The API will be released with Vue 3, but now you can try it with Vue 3 Composition API added to your Vue 2 app. In this tutorial, we’re gonna show you:

  • New Vue Composition API overview and comparison with classic Vue Options-based API
  • Examples to implement a Vue Component with new API: props, data, watchers, lifecycle hooks
  • Example to take advantage of new Vue 3 Composition API (function-based API): split Topics into Functions

Related Posts:
Vue v-slot tutorial with examples
Vue 3 CRUD example with Axios & Vue Router
Vue 3 Authentication with JWT, Vuex, Axios and Vue Router

Read More

Dart/Flutter List Tutorial with Examples

One of the most popular data structure in OOP is List. In this tutorial, we’ll show you many methods and functions to work with a List in Dart (also in Flutter). At the end, you’re gonna know:

  • Introduction to Dart List
  • How to create, initialize, access, modify, remove items in a List
  • Ways to iterate, find, filter, transform items of a List in Dart/Flutter
  • How to create List of objects in Dart/Flutter
  • Ways to sort a List (of objects) in Dart/Flutter
  • Initialize, iterate, flatten list of Lists

Related Posts:
Dart/Flutter – Convert Object to JSON string
Dart/Flutter – Convert/Parse JSON string, array into Object, List
Dart/Flutter – Convert List to Map & Map to List
Dart – Convert Object to Map and Vice Versa
Dart/Flutter – Sort list of Objects

Dart/Flutter Constructors tutorial with examples
Dart/Flutter String Methods & Operators tutorial with examples
Dart/Flutter Future Tutorial with Examples
Dart/Flutter Map Tutorial with Examples

Read More

How to parse a String into a number in Dart/Flutter

Converting String into Number is necessary for almost language. Dart is no exception. In this tutorial, we’re gonna look at ways to parse a String into a number (int & double) using parse() and tryParse() method. You also know how to catch Exception for invalid input string, or convert a Hex string to int in Dart/Flutter.

Related Posts:
Dart/Flutter – Convert/Parse JSON string, array into Object, List
Dart – Convert Object to Map and Vice Versa

Dart/Flutter Constructors tutorial with examples
Dart/Flutter String Methods & Operators tutorial with examples
Dart/Flutter Future Tutorial with Examples
Dart/Flutter List Tutorial with Examples
Dart/Flutter Map Tutorial with Examples

Read More