0

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.

Skeltar
  • 25
  • 1
  • 8

2 Answers2

1

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:

  1. 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").

  2. 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.

  3. 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.

KUSH42
  • 552
  • 2
  • 13
  • If I want to use the windows-shortcut how shut the path look like? For example I have the File test.txt and it is save in the appdata/roming folder and I want to use the %appdata%. – Skeltar Aug 27 '20 at 07:53
  • 1
    Simply call `System.getenv("APPDATA")`. This will return the absolute path of the appdata folder as a string, and you can use this absolute path just like you would any other. – KUSH42 Aug 27 '20 at 10:49
1

See this

You can access files with relative path like this way:

File file = new File("..\\..\\file.txt");
String fileAbsolutePath = file.getAbsolutePath();

Hint: This only works if the file is embedded to the project.