Home > Java > javaTutorial > body text

Detailed explanation of Java's method of obtaining environment variables and system properties

高洛峰
Release: 2016-12-17 13:17:11
Original
1501 people have browsed it

The concept of environment variables is not unfamiliar, it is the environment variable of the operating system.
System variables are variables maintained by java itself. Obtained through System.getProperty.
For different operating systems, there may be some inconsistencies in the processing of environment variables, such as: case insensitivity, etc.

Java gets environment variables
The way to get environment variables in Java is very simple:
System.getEnv() Get all environment variables
System.getEnv(key) Get the value of a certain environment variable

Map map = System.getenv();
Iterator it = map.entrySet().iterator();
while(it.hasNext())
{
  Entry entry = (Entry)it.next();
  System.out.print(entry.getKey()+"=");
  System.out.println(entry.getValue());
}
Copy after login

If It is a Windows system, and the printed values ​​are the same as the environment variables seen in "My Computer".

Java gets and sets system variables
The way Java gets environment variables is also very simple:
System.getProperties() Get all system variables
System.getProperty(key) Get the value of a certain system variable

Properties properties = System.getProperties();
Iterator it = properties.entrySet().iterator();
while(it.hasNext())
{
  Entry entry = (Entry)it.next();
  System.out.print(entry.getKey()+"=");
  System.out.println(entry.getValue());
}
Copy after login

In addition to obtaining system variables, you can also set the system variables you need through System.setProperty(key, value).

What system variables are set by java by default:

java.version Java runtime environment version

java.vendor Java runtime environment vendor

java.vendor.url Java vendor URL

java. home Java installation directory

java.vm.specification.version Java virtual machine specification version

java.vm.specification.vendor Java virtual machine specification vendor

java.vm.specification.name Java virtual machine specification name

java .vm.version Java virtual machine implementation version

java.vm.vendor Java virtual machine implementation vendor

java.vm.name Java virtual machine implementation name

java.specification.version Java runtime environment specification version

java .specification.vendor Java runtime environment specification vendor

java.specification.name Java runtime environment specification name

java.class.version Java class format version number

java.class.path Java class path

java. library.path List of paths searched when loading the library

java.io.tmpdir Default temporary file path

java.compiler Name of the JIT compiler to be used

java.ext.dirs Path to one or more extension directories

os.name The name of the operating system

os.arch The architecture of the operating system

os.version The version of the operating system

file.separator The file separator ("/" in UNIX systems)

path.separator Path separator (":" in UNIX systems)

line.separator Line separator ("/n" in UNIX systems)

user.name User's account name

user.home User's home directory

user.dir The current working directory of the user


Supplementary
1. In .bat; .cmd or .sh, some variables will be set by set,
For example, setDomainEnv.cmd of weblogic
set SUN_JAVA_HOME=C :OracleMiddlewarejdk160_21
What is set here is the environment variable
2. In the configuration of log4j, the generation path of the log file is sometimes configured.
For example, ${LOG_DIR}/logfile.log, LOG_DIR here is replaced by the system attribute variable.
3. Take a look at the java source code. When obtaining system variables through System.getProperties(), there will be a security check

  public static Properties getProperties() {
SecurityManager sm = getSecurityManager();
    if (sm != null) {
  sm.checkPropertiesAccess();
}
  
return props;
  }
Copy after login

When testing a single Java application, the SecurityManager in System is empty.
When the Applet is running, it will check the permissions in combination with the .policy file.

If you give an empty SecurityManager, you will find that a permission exception will be thrown.

public static void main(String[] args) {
  // TODO Auto-generated method stub
  System.setSecurityManager(new SecurityManager());
  //SecurityManager sm = System.getSecurityManager();
  //System.out.println(sm);
  System.getSecurityManager().checkPropertiesAccess();
}
Copy after login

The difference between System.getEnv() and System.getProperties()
Conceptually, system properties and environment variables are mappings between names and values. Both mechanisms can be used to pass user-defined information to the Java process. Environment variables have more of a global effect because they are visible not only to Java child processes, but to all child processes of the process in which they are defined. On different operating systems, their semantics are slightly different, for example, they are not case sensitive. For these reasons, environment variables are more likely to have unintended side effects. It's best to use system properties where possible. Environment variables should be used when global effects are required, or when an external system interface requires the use of environment variables (such as PATH).

The code is as follows:

public static void main(String [] args)
    {
       Map m = System.getenv();
       for ( Iterator it = m.keySet().iterator(); it.hasNext(); )
       {
           String key = (String ) it.next();
           String value = (String ) m.get(key);
           System.out.println(key +":" +value);
       }
       System.out.println( "--------------------------------------" );
       Properties p = System.getProperties();
        
       for ( Iterator it = p.keySet().iterator(); it.hasNext(); )
       {
           String key = (String ) it.next();
           String value = (String ) p.get(key);
           System.out.println(key +":" +value);
       }
    }
Copy after login


The input is as follows:

ANT_HOME:D:/program/devel/ant
PROCESSOR_ARCHITECTURE:x86
LOGONSERVER://RJ-WEIJIANJUN
HOMEDRIVE:C:
CATALINA_HOME:D:/program/server/Tomcat5.5
DXSDK_DIR:d:/Program Files/Microsoft DirectX SDK (August 2008)/
VS80COMNTOOLS:C:/Program Files/Microsoft Visual Studio 8/Common7/Tools/
SESSIONNAME:Console
HOMEPATH:/Documents and Settings/Administrator
TMP:C:/DOCUME~1/ADMINI~1/LOCALS~1/Temp
windir:C:/WINDOWS
PROCESSOR_IDENTIFIER:x86 Family 6 Model 15 Stepping 13, GenuineIntel
VS90COMNTOOLS:e:/Program Files/Microsoft Visual Studio 9.0/Common7/Tools/
SystemDrive:C:
USERPROFILE:C:/Documents and Settings/Administrator
PATHEXT:.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH
CommonProgramFiles:C:/Program Files/Common Files
NUMBER_OF_PROCESSORS:2
ComSpec:C:/WINDOWS/system32/cmd.exe
COMPUTERNAME:RJ-WEIJIANJUN
OS:Windows_NT
USERNAME:Administrator
CLIENTNAME:Console
TEMP:C:/DOCUME~1/ADMINI~1/LOCALS~1/Temp
USERDOMAIN:RJ-WEIJIANJUN
ALLUSERSPROFILE:C:/Documents and Settings/All Users
lib:C:/Program Files/SQLXML 4.0/bin/
PROCESSOR_LEVEL:6
SystemRoot:C:/WINDOWS
ClusterLog:C:/WINDOWS/Cluster/cluster.log
APPDATA:C:/Documents and Settings/Administrator/Application Data
Path:C:/WINDOWS/system32;C:/WINDOWS;C:/WINDOWS/System32/Wbem;C:/Program Files/Microsoft SQL Server/80/Tools/Binn/;C:/Program Files/Microsoft SQL Server/90/DTS/Binn/;C:/Program Files/Microsoft SQL Server/90/Tools/binn/;C:/Program Files/Microsoft SQL Server/90/Tools/Binn/VSShell/Common7/IDE/;C:/Program Files/Microsoft Visual Studio 8/Common7/IDE/PrivateAssemblies/;D:/program/devel/flex_sdk2/bin;D:/program/devel/ant/bin;C:/Program Files/Java/jdk1.6.0_07/bin;%JONAS_ROOT%/bin/nt;d:/program/devel/ant/bin
JAVA_HOME:C:/Program Files/Java/jdk1.6.0_07
FP_NO_HOST_CHECK:NO
PROCESSOR_REVISION:0f0d
ProgramFiles:C:/Program Files
Copy after login

The following is the output of the property:

-------------------------------- -------------------

java.runtime.name:Java(TM) 2 Runtime Environment, Standard Edition
sun.boot.library.path:D:/Program Files/MyEclipse 6.5/jre/bin
java.vm.version:1.5.0_11-b03
java.vm.vendor:Sun Microsystems Inc.
java.vendor.url:http://java.sun.com/
path.separator:;
java.vm.name:Java HotSpot(TM) Client VM
file.encoding.pkg:sun.io
sun.java.launcher:SUN_STANDARD
user.country:CN
sun.os.patch.level:Service Pack 2
java.vm.specification.name:Java Virtual Machine Specification
user.dir:D:/dev/eclipse/mye65/workspace/jmx
java.runtime.version:1.5.0_11-b03
java.awt.graphicsenv:sun.awt.Win32GraphicsEnvironment
java.endorsed.dirs:D:/Program Files/MyEclipse 6.5/jre/lib/endorsed
os.arch:x86
java.io.tmpdir:C:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/
line.separator:
  
java.vm.specification.vendor:Sun Microsystems Inc.
user.variant:
os.name:Windows 2003
sun.jnu.encoding:GBK
java.library.path:D:/Program Files/MyEclipse 6.5/jre/bin;.;C:/WINDOWS/system32;C:/WINDOWS;C:/WINDOWS/system32;C:/WINDOWS;C:/WINDOWS/System32/Wbem;C:/Program Files/Microsoft SQL Server/80/Tools/Binn/;C:/Program Files/Microsoft SQL Server/90/DTS/Binn/;C:/Program Files/Microsoft SQL Server/90/Tools/binn/;C:/Program Files/Microsoft SQL Server/90/Tools/Binn/VSShell/Common7/IDE/;C:/Program Files/Microsoft Visual Studio 8/Common7/IDE/PrivateAssemblies/;D:/program/devel/flex_sdk2/bin;D:/program/devel/ant/bin;C:/Program Files/Java/jdk1.6.0_07/bin;%JONAS_ROOT%/bin/nt;d:/program/devel/ant/bin
java.specification.name:Java Platform API Specification
java.class.version:49.0
sun.management.compiler:HotSpot Client Compiler
os.version:5.2
user.home:C:/Documents and Settings/Administrator
user.timezone:Asia/Shanghai
java.awt.printerjob:sun.awt.windows.WPrinterJob
file.encoding:GBK
java.specification.version:1.5
java.class.path:D:/dev/eclipse/mye65/workspace/jmx/bin;D:/program/lib/jmx/jmxtools.jar;D:/program/lib/log/commons-logging-1.1.1.jar;D:/program/lib/log/log4j-1.2.15.jar;D:/program/lib/registry/registry.jar
user.name:Administrator
java.vm.specification.version:1.0
java.home:D:/Program Files/MyEclipse 6.5/jre
sun.arch.data.model:32
user.language:zh
java.specification.vendor:Sun Microsystems Inc.
awt.toolkit:sun.awt.windows.WToolkit
java.vm.info:mixed mode
java.version:1.5.0_11
java.ext.dirs:D:/Program Files/MyEclipse 6.5/jre/lib/ext
sun.boot.class.path:D:/Program Files/MyEclipse 6.5/jre/lib/rt.jar;D:/Program Files/MyEclipse 6.5/jre/lib/i18n.jar;D:/Program Files/MyEclipse 6.5/jre/lib/sunrsasign.jar;D:/Program Files/MyEclipse 6.5/jre/lib/jsse.jar;D:/Program Files/MyEclipse 6.5/jre/lib/jce.jar;D:/Program Files/MyEclipse 6.5/jre/lib/charsets.jar;D:/Program Files/MyEclipse 6.5/jre/classes
java.vendor:Sun Microsystems Inc.
file.separator:/
java.vendor.url.bug:http://java.sun.com/cgi-bin/bugreport.cgi
sun.io.unicode.encoding:UnicodeLittle
sun.cpu.endian:little
sun.desktop:windows
sun.cpu.isalist:pentium_pro+mmx pentium_pro pentium+mmx pentium i486 i386 i86
Copy after login


For more detailed explanations of how to obtain environment variables and system properties in Java, please pay attention to the PHP Chinese website for related articles!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!