Trail: Essential Classes_Lesson: The Platform Environment

本文介绍如何使用Java的Properties类进行属性管理,并通过示例展示了如何从文件加载属性和将其保存到文件。同时,文章还介绍了如何利用Java获取系统环境变量并调整程序变量,以增强程序的灵活性和跨平台性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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();

 

 

 

 

 

 

 


 




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值