I am running a Java application from the command line. Can I specify a command line argument to set the current running directory to something other than where the application is actually going to run?
- 
                    Not sure that this is a duplicate, but can be helpful http://stackoverflow.com/questions/840190/changing-the-current-working-directory-in-java – khachik Dec 14 '10 at 18:30
 - 
                    Yes, that may be helpful. new File(parent, path) might work. I will have to try it. Reason why I posted this question is I am trying to use a profiler on a dll that my application loads. Since I have to essentially profile java.exe, the current working directory gets set to my jdk folder and throws off my relative paths in my application. – user538442 Dec 14 '10 at 18:33
 - 
                    Your profiler should have an option to set starting directory. Or maybe it is possible to write a BAT file and tell profiler to run it? – Sergei Tachenov Dec 14 '10 at 18:54
 - 
                    It does, but the application will not run when I set that for whatever reason – user538442 Dec 14 '10 at 19:20
 
4 Answers
There is a JVM argument -Duser.dir which can be used to set working directory for JVM.
- 441
 - 4
 - 3
 
- 
                    Don't do this unless you want some inconsistent behavior in your program. I.e. `new File("file.txt").getAbsolutePath()` and `new File("file.txt").getCanonicalPath()` respect the value of the property. But most of other methods of the `File` do not. – reddot Jul 05 '23 at 00:15
 
If it all possible I would rather use a script to run the java application and set the directory in the script:
#!/bin/sh
cd <your dir>
java <some arguments>
The JNI-solution may affect all kinds of relative paths in your application; for examples the classpath you put in.
- 12,237
 - 1
 - 40
 - 55
 
If you want to change the current directory, you'll have to use JNI and invoke a native API from your Java code. For example, for Windows you would use SetCurrentDirectory
- 1,228
 - 5
 - 20
 - 31
 
I found this SO post and it helped me solve my problem. Though I wanted to share something specific about IntelliJ that might trip somebody else up.
I have posted a picture below where the -Duser.dir flag is used and also the Working Directory text field is filled in.
In this situation, the Working Directory will be set to "JarLearning" rather than "2ndTry".
- 887
 - 1
 - 10
 - 15
 
