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
or Kotlin2.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:
- When run from the command line (e.g. with
kotlin myapp.jar
), it inherits the working directory from the shell running it — which might be your home directory, if you haven't used cd
to change it.
- When run from an IDE, the IDE will set the working directory. For example, in IntelliJ the run configuration you use will probably have a setting for the working directory; see these questions.
- When launched from the desktop, it might use your home directory (depending on the OS).
- When run from within Tomcat, the current directory is usually set from
$CATALINA_BASE
or $CATALINA_HOME
; see this question.
- When run from other programs, it'll depend upon the program.
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.