java中的Properties类

在项目中,经常会使用properties文件对项目相关参数进行设置,https://blog.csdn.net/Senton/article/details/4083127对properties类型文件的读取方式进行了总结,其中大多方法都是将文件转为InputStream,然后作为Properties类中load方法的参数,讲配置文件中的参数加载到虚拟机中来。本片文章对类Properties的用法和特点做了些总结。

Properties继承自java.util.Hashtable。

本文以java.lang.ClassLoader类的getSystemResourceAsStream()静态方法为例加载配置文件:
InputStream in = ClassLoader.getSystemResourceAsStream(name);//name为配置文件路径
Properties p = new Properties();
p.load(in);

load ( InputStream inStream)方法从输入流中读取属性列表(键和元素对)。通过对指定的文件(比如说上面的 test.properties 文件)进行装载来获取该文件中的所有键 - 值对。以供 getProperty ( String key) 来搜索。

使用Enumeration类可以遍历properties文件内容:
Enumeration enum1 = p.propertyNames();//得到配置文件的名字 
while(enum1.hasMoreElements()) {
      String strKey = (String) enum1.nextElement();
      String strValue = pps.getProperty(strKey);
      System.out.println(strKey + "=" + strValue);
}

getProperty ( String key),用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value。

Properties p = new Properties();
p.setProperty("name","zhangsan");
p.setProperty("age","25");
p.setProperty("birthday","20180815");
FileOutputStream file=null;
try {
      file = new FileOutputStream("test.txt");
      p.store(file,"commentsTest");
      file.close();
} catch (Exception e) {
      e.printStackTrace();
}

setProperty ( String key, String value) ,调用 Hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对

store ( OutputStream out, String comments),以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。其中comments是用来对配置文件做说明的,会以注释的形式出现在文件的第一行。


此外,Java虚拟机(JVM)有自己的系统配置文件(system.properties),可以通过下面的方式来获取:
Properties p = System.getProperties();
p.list(System.out);

在程序运行时的VM options中,通过-D也可以设置虚拟机参数,然后通过getProperty(key)获得参数值。

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值