0

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.

  1. I start the terminal in the default directory which is ~ (home directory). I type java -jar Desktop/Program.jar. ---> Test.txt is created in ~.

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

  • Did you check [this](https://stackoverflow.com/questions/320542/how-to-get-the-path-of-a-running-jar-file)? – BackSlash Apr 02 '18 at 09:06

1 Answers1

-1

As explained in this question you can find the path of your jar file by some odd operations like this:

  String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath();
      String decodedPath = URLDecoder.decode(path, "UTF-8");

After you find the path of the jar file you can pass this path as a first argument of the Paths.get method:

Files.write(Paths.get(decodedPath,"Test.txt") , "foo.txt".getBytes(), StandardOpenOption.CREATE);
Isa Hekmat
  • 758
  • 1
  • 7
  • 19
  • Thank you very much, this helped me out :) – pascal0506 Apr 02 '18 at 11:05
  • No. URLDecoder is for decoding form/URL keys and values, not for URLs themselves, despite its name. The correct mechanism is to convert the URL returned by `CodeSource.getLocation()` to a URI and construct a `File` around that. – user207421 Apr 03 '18 at 06:16