Properties简单解析实现及其工具化实现

properties文件

bookName = The Kite Runner
price = 25.6
author = Khaled Hosseini

简单实现properties解析

package com.mec.parser.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;

public class TestForProperties {
	public static void main(String[] args) {
		Properties properties = new Properties();
		InputStream is = Class.class.getResourceAsStream("/test.properties");
		try {
			properties.load(is);
			Enumeration<Object> keys = properties.keys();  // 获取properties文件中的键集合
			// Enumeration是一个泛型类,里面存储的是键值对数据集合
			while(keys.hasMoreElements()) {
				String key = (String) keys.nextElement();
				String value = properties.getProperty(key);
				System.out.println(key + " " + value);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
	}
}

运行结果

author: Khaled Hosseini
price: 25.6
bookName: The Kite Runner

工具代码

package com.mec.util.parser;

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

public class PropertiesParser {
	private static final Map<String, String> propertyMap = new HashMap<>();
	
	public PropertiesParser() {
		
	}
	
	public static void loadProperties(String path) {
		InputStream is = PropertiesParser.class.getResourceAsStream(path);
		loadProperties(is);
	}
	
	public static void loadProperties(InputStream is) {
		Properties properties = new Properties();
		
		try {
			properties.load(is);
			Set<Object> keySet = properties.keySet();
			Iterator<Object> iterator = keySet.iterator();
			while(iterator.hasNext()) {
				String key = (String) iterator.next();
				String value = properties.getProperty(key);
				propertyMap.put(key, value);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	public static Set<String> keySet() {
		return propertyMap.keySet();
	}
	
	public static String value(String key) {
		return propertyMap.get(key);
	}
	
}

使用

工具测试代码

package com.mec.util.parser;

public class TestForProperties {
	public static void main(String[] args) {
		PropertiesParser.loadProperties("/test.properties");
		String bookName = String.valueOf(PropertiesParser.value("bookName"));
		System.out.println("书名:" + bookName);
		String authorName = String.valueOf(PropertiesParser.value("author"));
		System.out.println("作者:" + authorName);
		double price = Double.valueOf(PropertiesParser.value("price"));
		System.out.println("价格:" + price);
		
	}

}

运行结果

书名:The Kite Runner
作者:Khaled Hosseini
价格:25.6

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值