128

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)?

Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
johnny-b-goode
  • 3,792
  • 12
  • 45
  • 68
  • 2
    As stated in http://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. – Seldom 'Where's Monica' Needy Oct 12 '16 at 19:52

4 Answers4

181

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.

Uooo
  • 6,204
  • 8
  • 36
  • 63
martinez314
  • 12,162
  • 5
  • 36
  • 63
  • 3
    Already read it before posting. But "User working directory" is not a best explanation, hope you agree. – johnny-b-goode Apr 26 '13 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? – Marcin Kapusta Mar 19 '19 at 11:21
8

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

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
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)

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • A value is needed only during junit test execution by maven system. – johnny-b-goode Apr 26 '13 at 14:54
  • 2
    and when you change it on the MAC, it breaks things like this test https://stackoverflow.com/questions/45130661/user-dir-property-broken-on-osx-jdk-1-8-0-111-how-about-other-os-versions :( :( – Dean Hiller Jul 16 '17 at 16:10
6

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

  • 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 Oct 09 '20 at 15:50