Properties文件解析详解,以及工具化。

1.首先展示下Properties解析过程

        public static void main(String[] args) {
                //输入流
		InputStream is = PropertiesParser.class.
                         getResourceAsStream("/first.properties");
                //创建Properties对象
		Properties properties = new Properties();
		try {
                        //加载文件
			properties.load(is);
                        //获取所有的键
			Enumeration<Object> keys = properties.keys();
			while(keys.hasMoreElements()) {
                                //遍历键集合,得到key 和 value输出
				String key = (String) keys.nextElement();
				String value = properties.getProperty(key);
				System.out.println(key + ":" + value);
			}	
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

2.properties工具化

package com.mec.excise;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class PropertiesParse {
        //properties对象只需要一份即可所以设置为静态成员。
	private static Properties properties;
        //将所有的键值对放在map里方便查找,加快程序运行速度。
	private static Map<String, String> map;
	
	static {
		properties = new Properties();
		map = new HashMap<String, String>();
	}
	
        //加载文件
	public static void loading(String path){
		InputStream is = Class.class.getResourceAsStream(path);
		loading(is);	
	}
	//重载加载文件
	public static void loading(InputStream is){
		try {
			properties.load(is);
			PutSet();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	//将所有的键,值,放到map里  
	private static void PutSet() {
		Enumeration<Object> em = properties.keys();
		while(em.hasMoreElements()) {
			String key = (String) em.nextElement();
			String value = properties.getProperty(key);
			map.put(key, value);
		}
	}
	//通过键得到对应的值
	public static String getvalue(String key) {
		return map.get(key);
	}
	//得到键集合。
	public static Set<String> KeySet() {
		return map.keySet();
	}
}

3.展示应用,只需两三行代码就完成解析。

package com.mec.test;

import com.mec.excise.PropertiesParse;

public class PropertiesParseTest {
	public static void main(String[] args) {
		new PropertiesParse();
		PropertiesParse.loading("/first.properties");
		System.out.println(PropertiesParse.getvalue("id"));
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值