Java Properties基础知识总结

在Java语言中,使用一种以.properties为扩展名的文本文件作为资源文件,该类型的文件的内容格式为类似:
some_key=some_value #注释描述
还有一种是使用xml文件保存项目的配置信息,同样可以使用Properties类解析。

xml配置文件格式:

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">  
<properties>  
<comment>hello world</comment>  
<entry key="foo">bar</entry>  
<entry key="fu">baz</entry>  
</properties>


API讲解

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

它提供了几个主要的方法:
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("
The foo property: " +  prop.getProperty("foo"));
	}
}


原文地址:https://www.cnblogs.com/archermeng/p/7537059.html