properties java 层次_Java Properties基础知识总结

在Java语言中,使用一种以.properties为扩展名的文本文件作为资源文件,该类型的文件的内容格式为类似:

some_key=some_value #注释描述

还有一种是使用xml文件保存项目的配置信息,同样可以使用Properties类解析。

xml配置文件格式:

hello world

bar

baz

API讲解

Properties 类表示了一个持久的属性集。Properties 可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串。

eff99379fe13162554ff45d5ec1c50e3.png

它提供了几个主要的方法:

1. getProperty ( String key)

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

2. load ( InputStream inStream)

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

3. setProperty ( String key, String value)

调用 Hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对。

4. store ( OutputStream out, String comments)

以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。

5. clear ()

清除所有装载的键 - 值对。该方法在基类中提供。

应用举例

1、读取.properties文件指定key的value值代码示例如下(web项目):

public static String getProperties(String key) throws Exception {

String value = "";

InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("public.properties");

Properties properties = new Properties();

properties.load(inputStream);

value = properties.getProperty(key);

inputStream.close();

return value;

}

2、读取xml配置跟读取kv配置没差别,就是把load换成xml对应的loadFromXML方法,代码如下:

public class LoadSampleXML {

public static void main(String args[]) throws Exception {

Properties prop = new Properties();

FileInputStream fis = new FileInputStream("sampleprops.xml");

prop.loadFromXML(fis);

prop.list(System.out);

System.out.println("\nThe foo property: " + prop.getProperty("foo"));

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值