29

How do I change the user.home system property from outside my java program, so that it thinks it's a different directory from D:\Documents and Settings\%USERNAME%? Via environment variables, or VM arguments?

tekumara
  • 8,357
  • 10
  • 57
  • 69

2 Answers2

40

Setting VM argument should work:

java -Duser.home=<new_location> <your_program> 

Here's a test case:

public class test {
  public static void main(String[] args) {
    System.out.println(System.getProperty("user.home"));
  }
}

Tested with java 1.5.0_17 on Win XP and Linux

java test
/home/ChssPly76

java -Duser.home=overwritten test
overwritten 
ChssPly76
  • 99,456
  • 24
  • 206
  • 195
  • 1
    I've tried it too, works just fine - see my update for code sample. What java version have you tried it with? – ChssPly76 Oct 01 '09 at 00:22
  • It could be a shell escaping issue. – daveb Oct 01 '09 at 00:30
  • 2
    oh hoh! - I invoked it as "java test -Duser.home=asdf", if I do "java -Duser.home=asdf test" it DOES work. It vaguely reminds me about something to do with the way command-line arguments are processed. Thanks. – weiji Oct 01 '09 at 00:41
  • 6
    @weiji: yes ... the java command line syntax REQUIRES the vm args to be before the class name. If you put them after the class name, 'java' will assume they are regular arguments for your app, and pass them to the 'main' method as part of the 'args' array. – Stephen C Oct 01 '09 at 01:39
26

If you want to set user.home for all Java programs, you can use the special environment variable _JAVA_OPTIONS.

But note that a difficult to suppress warning message will be printed.

$ export _JAVA_OPTIONS=-Duser.home=/some/new/dir
$ java test
Picked up _JAVA_OPTIONS: -Duser.home=/some/new/dir
/some/new/dir
Community
  • 1
  • 1
joecracker
  • 509
  • 5
  • 7