Home > Blockchain >  Can't read file in kotlin even though the file is in the same path as main.kt
Can't read file in kotlin even though the file is in the same path as main.kt

Time:09-21

I'm currently learning kotlin. Right now I am trying to learn file reading. For that I'm following the tutorial on Baeldung: https://www.baeldung.com/kotlin/read-file. The problem I ran into is that the text file i have created and saved in the same folder as main.kt (../src/main/kotlin) is not being read in. It does not exist according to Intelij.

Here the functions I used

fun readFileLineByLineUsingEachLine(filename: String) = File(filename).forEachLine {
    println(it)
}

and

val inputStream: InputStream = File ("Kotlin2.txt").inputStream()
val inputString = inputStream.reader().use {it.readText()}
println (inputString)

I am using Ubuntu which I do not have much experience with. I hope I can find some help here.

Thank you.

CodePudding user response:

The current directory, where it looks for the file, is not the directory that contains your main.kt. You can see where it's looking by making this small change:

val inputStream: InputStream = File("Kotlin2.txt").absoluteFile.inputStream()

The absoluteFile "property" (which is actually a call to getAbsoluteFile()) makes it print an error message containing the full path.

  • Related