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.
2
Answers
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:
The
absoluteFile
"property" (which is actually a call togetAbsoluteFile()
) makes it print an error message containing the full path.This is almost certainly because the current working directory isn’t what you think it is!
An absolute pathname (e.g.
/home/alice/mydir/myfile.txt
) will always refer to the same file; but a relative pathname (e.g.mydir/myfile.txt
orKotlin2.txt
) can refer to different files, depending on the current working directory.For a Kotlin (or Java) program, the current working directory will depend on how you run the program:
kotlin myapp.jar
), it inherits the working directory from the shell running it — which might be your home directory, if you haven’t usedcd
to change it.$CATALINA_BASE
or$CATALINA_HOME
; see this question.Your program can get its current working directory with e.g.
Path.of("").toAbsolutePath()
; see this question. (There doesn’t seem to be a general way to change it while the program is running, though this question mentions some workarounds.)So the solution is either to move your file into the right directory, or access it via an absolute pathname — or at least, one that’s relative to the current directory.
Also worth mentioning that configuration files and other resources are generally not located directly from the filesystem, but accessed as system resources, which allows much more flexibility in how apps are installed and run. Frameworks/platforms such as Spring or Android also provide their own ways to access resource files.