Trail: Essential Classes_Lesson: The Platform Environment

java.util.Properties可以以键值对的方式管理属性,键和值都是String类型

是java.util.Hashtable的子类

. . .
// create and load default properties
Properties defaultProps = new Properties();
FileInputStream in = new FileInputStream("defaultProperties");
defaultProps.load(in);//载入属性文件到内存
in.close();

// create application properties with default
Properties applicationProps = new Properties(defaultProps);//另一个构造

// now load properties
// from last invocation
in = new FileInputStream("appProperties");
applicationProps.load(in);
in.close();
. . .
FileOutputStream out = new FileOutputStream("appProperties");
applicationProps.store(out, "---No Comment---");//保存到文件
out.close();

系统的环境变量跟这类似

import java.util.Map;

public class EnvMap {
    public static void main (String[] args) {
        Map<String, String> env = System.getenv();//得到环境变量map
        for (String envName : env.keySet()) {
            System.out.format("%s=%s%n",
                              envName,
                              env.get(envName));
        }
    }
}

ProcessBuilder可用来运行程序,ProcessBuilder.environment可调整程序变量

ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
 Map<String, String> env = pb.environment();
 env.put("VAR1", "myValue");
 env.remove("OTHERVAR");
 env.put("VAR2", env.get("VAR1") + "suffix");
 pb.directory(new File("myDir"));
 Process p = pb.start();

要注意环境变量跟操作系统有关,具体内容会有区别

Preferences API

manifest

JNLP file

java.util.ServiceLoader

System.getProperty("path.separator")
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);
    }
}

SecurityManager appsm = System.getSecurityManager();

发表评论