Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading