Java 获取和设置系统属性


#Java 笔记


系统属性:system property。

获取所有的属性

import java.util.Properties;

public class TestProperty {

    public static void main(String[] args) {
        Properties properties = System.getProperties();
        for (Object key : properties.keySet()) {
            System.out.println(key + " : " + properties.getProperty((String) key));
        }
    }
}

运行结果示例(省略部分内容):

java.vm.version : 25.161-b12
gopherProxySet : false
sun.arch.data.model : 64
user.language : zh
java.specification.vendor : Oracle Corporation
awt.toolkit : sun.lwawt.macosx.LWCToolkit
java.vm.info : mixed mode
java.version : 1.8.0_161
java.vendor : Oracle Corporation
file.separator : /
java.vendor.url.bug : http://bugreport.sun.com/bugreport/
sun.io.unicode.encoding : UnicodeBig
sun.cpu.endian : little
sun.cpu.isalist : 

获取指定属性

public class TestProperty {

    public static void main(String[] args) {
        String value = System.getProperty("java.version");
        System.out.println(value);
    }
}

运行结果:

1.8.0_161

自定义属性

Java 会自带很多系统属性,我们也可以自定义,比如:

public class TestProperty {

    public static void main(String[] args) {
        String value = System.getProperty("name");
        System.out.println(value);
    }
}

运行:

▶ javac TestProperty.java
▶ java -Dname=1234 TestProperty
1234
▶ java TestProperty
null


( 本文完 )