136

I want to use user.dir dir as a base dir for my unit tests (that creates a lot of files). Is it correct that this property points to the current working directory (e.g. set by the 'cd' command)?

1
  • 2
    As stated in stackoverflow.com/a/840229/3159183, keep in mind that the -Duser.dir flag affects File objects (if they're not given a full path) but not FileOutPutStream objects. If you want to ensure the default directory matches for both, you should cd before you start Java. Commented Oct 12, 2016 at 19:52

4 Answers 4

190

It's the directory where java was run from, where you started the JVM. Does not have to be within the user's home directory. It can be anywhere where the user has permission to run java.

So if you cd into /somedir, then run your program, user.dir will be /somedir.

A different property, user.home, refers to the user directory. As in /Users/myuser or /home/myuser or C:\Users\myuser.

See here for a list of system properties and their descriptions.

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

3 Comments

Already read it before posting. But "User working directory" is not a best explanation, hope you agree.
Is that mean that on tomcat configuration for all java versions if user.dir is pointing to /usr/share/tomcat and in config we add something like this: file:./config then it will be pointing to /usr/share/tomcat/config always?
@MarcinKapusta No. Not unless tomcat guarantees this. Generally relying on 'working directory' is a fantastic idea for command line tools (which are rarely written in java) and a terrible idea for anything else: You'd write your code that assumes the 'workign dir' is /usr/share/tomcat, and the way you start tomcat on your system that's true, but then somebody installs the lot on a different OS, or the service infra of your OS is changed, and all of a sudden your java app breaks.
10

user.dir is the "User working directory" according to the Java Tutorial, System Properties

Comments

8

Typically this is the directory where your app (java) was started (working dir). "Typically" because it can be changed, eg when you run an app with Runtime.exec(String[] cmdarray, String[] envp, File dir)

2 Comments

A value is needed only during junit test execution by maven system.
and when you change it on the MAC, it breaks things like this test stackoverflow.com/questions/45130661/… :( :(
7

System.getProperty("user.dir") fetches the directory or path of the workspace for the current project

1 Comment

It normally fetches the current working directory, like you get from the pwd command, but it looks like if you run with e.g. mvn -f /path/to/project, maven will effectively cd /path/to/project internally before running tests.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.