ReadSystemProperties

public class ReadSystemProperties {
	public static void main(String[] args) {
		// 通过获得系统属性构造属性类 prop
		Properties prop = new Properties(System.getProperties());
		// 在标准输出中输出系统属性的内容
		prop.list(System.out);
                //测试一下user.dir的内容
		System.out.println(System.getProperty("user.dir"));
	}
}

 从输出中可以看到很多内容,比如源文件的编码(file.encoding),文件分隔符(file.separator)等等。

 

 其实这个获取的是JVM系统环境属性 ,通过这个属性可以获得一些关于当前操作系统的一些基本信息。

 

System中有一个方法是getenv(),返回一个Map,可以显示所有的操作系统的环境变量,代码如下:

 

for (Map.Entry<String, String> entry : System.getenv().entrySet()) {
			System.out.println(entry.getKey() + ": " + entry.getValue());
		}
 

 

如果要读取properties文件,那么一般的写法是怎么样的呢?

 

Properties prop = new Properties();
InputStream in = TestFile.class.getClassLoader().getResourceAsStream(
				"map2.properties");
prop.load(in);

 注意map2.properties文件要在classpath中,要不会出现文件找不到异常(filenotfoundexception),如果要遍历文件的键值对,那么该怎么做呢?

Set<Object> keyValue = prop.keySet();
		for (Object o : keyValue) {
			String key = (String) o;
			System.out.println(key);
			System.out.println(prop.getProperty(key));
		}

 

还可以通过ResourceBundle读取properties文件,例如properties文件是这样的:

 

    map.properties文件

 

JCP=HAPPY
Spec=Special
HAPPY=JCP
Welcome=HELLOWORLD
 
ResourceBundle resource = ResourceBundle.getBundle("map");
System.out.println(resource.getString("JCP"));

 注意代码中的文件名不需要写后缀,那么这段代码的输出为HAPPY。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值