Hi all,
How can I get the System Variable value which is present in MyComputer -> Properties -> Advanced -> Environment Variables -> System Variables in Java?
Hi all,
How can I get the System Variable value which is present in MyComputer -> Properties -> Advanced -> Environment Variables -> System Variables in Java?
Use the System.getenv()
method, passing the name of the variable to read.
Google says to check out getenv():
Returns an unmodifiable string map view of the current system environment.
I'm not sure how system variables differ from environment variables, however, so if you could clarify I could help out more.
To clarify, system variables are the same as environment variables. User environment variables are set per user and a different whenever a different user logs in. System wide environment variables are the same no matter what user logs on.
To access either the current value of a system wide variable or a user variable in Java, see below:
String javaHome = System.getEnv("JAVA_HOME");
For more information on environment variables see this wikipedia page.
Also make sure the environment variable you are trying to read is properly set before invoking Java by doing a:
echo %MYENVVAR%
You should see the value of the environment variable. If not, you may need to reopen the shell (DOS) or log off and log back on.
Hi.. I have used System.getenv() method.. Itsprinting value if i give "System.out.println(System.getenv("JAVA_HOME"));" and its showing null value if i give system variable created by me ("System.out.println(System.getenv("DBE"));"
Have you tried rebooting since you set the environment variable?
It appears that Windows keeps it's environment variable in some sort of cache, and rebooting is one method to refresh it. I'm not sure but there may be a different method, but if you are not going to be changing your variable value too often this may be good enough.
There are a few details of interest when getting system/environment properties.
First, System.getEnv(String)
was introduced way-back-when, then deprecated. The deprecation (foolishly, IHMO) continued all the way into JSE 1.4.
It got re-introduced in JSE 5.
Those are set using the Environment Variables panel in Windows. Changes to the variables many not get picked up until your current VM is shutdown, and the CMD.exe instance exited.
In contrast to the environment properties, Java also has Java system properties, accessible through System.getProperties()
. These variables can be initialized when the VM is started using a series -Dname=value
command line arguments. For example, the values for the properties maxInMemory
and pagingDirectory
are set in the command below:
C:\> java.exe -DmaxInMemory=100M -DpagingDirectory=c:\temp -jar myApp.jar
These properties can be modified at runtime, barring security policy restrictions.