java的System Properties

     java平台自身使用Properties对象来维护自己的配置。系统类维护一个描述当前工作环境的Properties对象。系统属性包含当前用户信息、java运行时环境的当前版本、文件路径的分隔符等信息。

Key Meaning
"file.separator" Character that separates components of a file path. This is "/" on UNIX and "\" on Windows.
"java.class.path" Path used to find directories and JAR archives containing class files. Elements of the class path are separated by a platform-specific character specified in thepath.separator property.
"java.home" Installation directory for Java Runtime Environment (JRE)
"java.vendor" JRE vendor name
"java.vendor.url" JRE vendor URL
"java.version" JRE version number
"line.separator" Sequence used by operating system to separate lines in text files
"os.arch" Operating system architecture
"os.name" Operating system name
"os.version" Operating system version
"path.separator" Path separator character used in java.class.path
"user.dir" User working directory
"user.home" User home directory
"user.name" User account name

安全性考虑:访问系统属性会受到平台安全性机制的限制。

读系统属性:系统类有两个方法读取系统属性 getProperty() 和getProperties()。

有两个不同的getProperty()

1.getProperty(String key) 通过key值查找对应的Value,如果没有找到返回null.

2.getProperty(String key String defaultValue) 通过 key值查找对应的Value,如果没有找到则返回 defaultValue.

getProperties()

写系统属性:System.setProperties()

系统使用System.setProperties()修改系统属性。

要注意的是:改变系统属性是具有潜在危险的,所以应当特别的谨慎

举一个例子:PropertiesTest类 在myProperties中加入下面内容

subliminal.message=Buy StayPuft Marshmallows!

import java.io.FileInputStream;
import java.util.Properties;

public class PropertiesTest {
    public static void main(String[] args) throws Exception {
        // set up new properties object
	// from file "myProperties.txt"
        FileInputStream propFile = new FileInputStream(
                                           "myProperties.txt");
        Properties p = new Properties(System.getProperties());
        p.load(propFile);

        // set the system properties
        System.setProperties(p);
	// display new properties
        System.getProperties().list(System.out);
    }
}


System.setProperties改变了当前运行的应用程序的系统属性,这些改变没有被持久化,也就是说,这个改变不会影响以后的对于系统属性的调用(重启jvm)或者是其他的应用程序。系统属性会在每次重启后被重新初始化。

原文地址:https://www.cnblogs.com/mengjianzhou/p/5986902.html