0

Firstly I' like some help to edit the question because I can't explain my self properly.

Straight up, I have an application that receives files through socket connection and then saves them in the computer. The problem is that this application runs as a .jar file, and I don't know what file directory to use at the FileOutputStream() method. I am currently using the "C:\Users\My_User\Desktop\My_Project..." directory, but this is not affordable once many clients will use this and the directory may get lost depending on the client (some of them might be Linux as well).

How can I save the files at the same place where the .jar is, without having to write the whole Windows directory?

Thanks, since now

  • Possible duplicate of [How to get the path of a running JAR file?](https://stackoverflow.com/questions/320542/how-to-get-the-path-of-a-running-jar-file) – Elye M. Jan 30 '18 at 18:03

2 Answers2

2

Assumption: You are running an executable jar file by double-clicking on it.

By default, if you create a File object with a name f.txt, without any specific path, it will create the file f.txt in the same directory where your jar is running. eg:

If you are running your jar in C:\Users\My_User\Desktop\My_Project directory, and your code creates a file f.txt like the following:

File f = new File("f.txt");

then the location of f.txt will be C:\Users\My_User\Desktop\My_Project\f.txt

If you want to store the files at a specific location inside the User's home directory, Zaki's answer would be helpful.

Pankaj Singhal
  • 15,283
  • 9
  • 47
  • 86
  • No, it will create the file in the default working directory. For example, if you are in a Command Prompt window and type `cd /d D:\tmp` followed by `java -jar C:\Users\My_User\Desktop\My_Project\my_app.jar` then the files it creates will be placed in `D:\tmp` - not the same place as the jar. – DodgyCodeException Jan 30 '18 at 18:07
  • 1
    That was the assumption. Probably, I should mention that in the answer. – Pankaj Singhal Jan 30 '18 at 18:09
2

You can use for example:

final String RESOURCES_DIR = System.getProperty("user.dir") + File.separator + someSpecificLocation;

And then you can create file with RESOURCES_DIR as directory + the name of the file. That will save your file in the same directory nomather where the application is deployed.