I am trying to make a program which creates a text file in the directory of the jar-file. To do that, I use the class Files:
Files.write(Paths.get("Test.txt"), "foo.txt".getBytes(), StandardOpenOption.CREATE);
I noticed that when I export the program and start it out of the console by typing java -jar Program.jar, the directory where the Test.txt file is created is dependent of the directory from which I am starting it.
Example:
The Program.jar is located in ~/Desktop.
I start the terminal in the default directory which is ~ (home directory). I type java -jar Desktop/Program.jar. ---> Test.txt is created in ~.
I start the terminal in the default directory and type cd Desktop and then java -jar Program.jar ---> Test.txt is created in ~/Desktop.
I think that the reason is that Paths.get() calls FileSystems.getDefault() which returns the Terminal's directory as "root" for the program. When I start a GUI application on the Desktop which creates a file using the same method as described above, the file is created in the home directory too, I think that it could be because on double-click the command java-jar ~/Desktop/GUIProgram.jar is called.
Am I right with my thoughts? What could I do to achieve my goal of creating a file in the same directory as the program? In the end, I want a GUI application so it's not a solution to always use the terminal and cd to the Desktop directory. Do I have to use another class for I/O operations? I'd love to keep using Files because it's so simple and short.
Thanks in advance for your help!