23

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?

4
  • Not sure that this is a duplicate, but can be helpful stackoverflow.com/questions/840190/… Commented Dec 14, 2010 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. Commented Dec 14, 2010 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? Commented Dec 14, 2010 at 18:54
  • It does, but the application will not run when I set that for whatever reason Commented Dec 14, 2010 at 19:20

4 Answers 4

44

There is a JVM argument -Duser.dir which can be used to set working directory for JVM.

Sign up to request clarification or add additional context in comments.

1 Comment

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

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.

Comments

0

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

2 Comments

I am using JNI so this might be a possible solution.
This would make your code completely non-portable, of course.
0

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.

"Working Directory" field has lower precedence than the -Duser.dir flag.

In this situation, the Working Directory will be set to "JarLearning" rather than "2ndTry".

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.