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.
- The
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]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | package exercise01 import java.io.File /** * Created by Turreta.com on 12/6/2017. */ fun main(args: Array<String>) { File(ClassLoader.getSystemResource("TestData01.txt").file).forEachLine { println(it) } } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public static void main(String... a) { String fileName = ClassLoader.getSystemResource("TestData01.txt").getFile(); /** * To remove prefixed "/", e.g., /C:/ */ fileName = fileName.substring(1); try (Stream<String> stream = Files.lines(Paths.get(fileName))) { stream.forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); } } |
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