I'm using IntelliJ Idea and I try to read a txt file from a different location in the project. I don't want to use an absolute path like C:/User/... because if the project is moved to a different location the project wouldn't work anymore. I'm not sure how the path should look like.
If you are using relative Paths, this will generally also mean that it will not work anymore once you are changing directory structure.
Example (I am assuming Windows here):
The java-application resides C:\Tools
. You are using a relative Path (..\file.txt
). This would access C:\file.txt
(..
moves up one directory).
If you moved the App to C:\Tools\JavaApp
it wouldn't work anymore, since ..\file.txt
now points to C:\Tools\file.txt
).
You have several options (three just from the top of my head; there are multiple ways to do this) to achieve what you want:
Use an alias to access the file. Here is a list of windows-shortcuts that will work (I am assuming that you are using Windows). For example: Save the file to %appdata%
, and it will always save to the current user's appdata folder. To resolve the windows shortcut to an absolute path in Java, use System.getenv("APPDATA")
.
Read the file from the program's working directory This is probably what you meant by using relative paths: The current working directory of a java application is the directory the program is being run from. This will require you to place the file to be read in the same folder as your project/jar-file, or to use relative paths to navigate to the file's location, for example a sub-folder in your working directory where you would place the file.
Use a .properties file to declare the file location You could also read the file location from a properties file, however you can only change the path at compile time. Here's an article on how to use .properties-files.