How to read File in Kotlin

This tutorial shows you how to read File in Kotlin using InputStream or BufferedReader.


>>> Refer to: JavaSampleApproach.com

I. Technology

– Java 1.8
– Kotlin 1.1.2

II. Overview

1. Goal

Read file: all lines/by line using InputStream or BufferedReader or File directly.

2. Steps to do

– Create:
+ InputStream from File, then get BufferedReader using bufferedReader() method
+ BufferedReader from File.
– Use:
+ Closeable.use() method with Reader.readText() method inside block. Closeable.use() will automatically close the input at the end of the lambda’s execution:

+ Reader.useLines() method with Kotlin Sequence (a sequence of all the lines) inside block. Reader.useLines() will automatically close the reader once the processing is complete:

+ File.useLines() method with Kotlin Sequence (a sequence of all the lines) inside block. It will close the reader once the processing is complete:

+ File.readLines() method to return a List<String>:

III. Practice

0. kotlination.txt

1. Use InputStream
1.1 Read All Lines

Check Result:

1.2 Read By Line

Check Result:

2. Use BufferedReader
2.1 Read All Lines

Check Result:

2.2 Read By Line

Check Result:

3. Use File directly

Check Result:

4 thoughts on “How to read File in Kotlin

  1. I have created the kotlination.txt file under resource folder. \app\src\main\res\
    I am getting exception ‘no such file or directory’
    Could you please help me to resolve the issue?

    1. Hi Milind,

      Because we don’t indicate path for kotlination.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 \app\src\main\res\ folder, just change the path:
      File(“kotlination.txt”) -> File(“src/main/res/kotlination.txt”)

      Best Regards!

  2. You could simplify to

    First you could use useLines directly on the file, and second you should not create an auxiliary collections like in Java < 8 days.

    1. Hi Christian,

      Thank you for your suggestion. We updated that method. But we think it should be:

      Best Regards,

Add Comment