Software Development

Kotlin – Read file line by line from Classpath

This post shows how to leverage Java libraries (from our underlying JVM) to read file line by line from classpath using Kotlin. Also, IntelliJ IDE is used for this post but can easily be replicated in Eclipse.

Requirements

  • IntelliJ IDEA Ultimate 2016.3
    • The Community Edition may be enough but we have not tried it.
  • Kotlin Version 1.1
  • Windows 10 Enterprise

IntelliJ Project and Files

We have a very simple project that contains two (2) files – TestData01.txt and EX01.kt.

[wp_ad_camp_1]

Codes and Data File

Here is our Kotlin program.

[wp_ad_camp_2]

If you are really new to Kotlin, the following provide short explanations on how the codes work.

In Java

In Java, the codes are equivalent to:

So, in Kotlin

The codes create a java.io.File object and uses the file property to get the name (path + name) of the file in the file system. The forEach construct, which is from Kotlin, loops through the content of the file.

The it variable

[wp_ad_camp_3]

The it variable represents the current item in the iteration. You cannot use other variables but it.

Test Out the codes

References

[wp_ad_camp_4]

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-file/for-each-line.html

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like