How to add new System Properties in java
Asked Answered
G

3

30

Is it possible to add new values to Java System Properties. If there is any how can introduce new keys with there corresponding values in Java System Properties.

Gilli answered 16/3, 2012 at 12:2 Comment(0)
N
53

Either System.setProperty or use the -Dname=value flag when you start the JVM

Narvik answered 16/3, 2012 at 12:5 Comment(8)
Thanks for the reply. The code using System.setProperty(String key, String value) ran fine but I am unable to get the output with getProperty(String key). I generates a null value.Gilli
Also when I tried to check all the values in System properties via getProperties(), the newly entered property wasn't listed in it.Gilli
You know that these properties only exist for the running process, right? You're not trying to check them in a different process, or using the same program but after stopping and restarting it? The only other thing I can suggest is that either you never actually got to the line of code that set the property, or else you got there after you'd run the code that tries to fetch the value back.Narvik
I didn't know that it existed only for the running process. But I think I introduced a new key and checked it out in the same program. Here have a look at the code sample I am using,Gilli
System.setProperty("getsuga.tenhou","C:\\tanay\\getsuga"); System.out.print(System.getProperty("getsuga.tenshou"));Gilli
The name of the property you are setting is not the same as the name you are trying to get. One has and extra 's' in it.Narvik
Oh man, silly mistakes. Sorry for wasting your time on something like this. Is there any method to set these properties permanently so that they can be used outside the scope of the program?Gilli
No. Normally, you'd write a shell script or batch file to start up your Java program and set all your system properties there. But normally, a configuration file is a better route forward for this kind of thing.Narvik
C
8

Yes:

public static void main(String args[]) {
    String key = "a new property";
    System.setProperty(key, "a property with a value");
    System.out.println(System.getProperty(key));
}
Cousins answered 16/3, 2012 at 12:6 Comment(1)
Thanks for the reply, I tried your method. But I get a null value when I try getProperty(). I am pretty sure that I typed in the property key correctly. Please advise.Gilli
L
3
System.setProperties(properties object);

This will set the system properties.

If you want to set a specified property, then use

System.setProperty(key, value);//Both key and value should be string.

NOTE: This will first check the permission and then set it. If permission denied, then SecurityException may occur.

Littles answered 16/3, 2012 at 12:4 Comment(1)
System.setProperties(properties object) will override any existing System properties. Use with caution.Pay

© 2022 - 2024 — McMap. All rights reserved.