134

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

188

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.

2
  • 3
    Already read it before posting. But "User working directory" is not a best explanation, hope you agree. Commented Apr 26, 2013 at 14:53
  • 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? Commented Mar 19, 2019 at 11:21
10

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

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
6

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

1
  • 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.
    – rjmunro
    Commented Oct 9, 2020 at 15:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.