Java解析 properties

方法一

import java.io.InputStream;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.ResourceBundle;

import org.junit.Test;

/**
 * 获取*.properties配置文件中的内容 ,常见的两种方法:
 * 
 * 
 * 
 */
public class ReadProperties {
	// 方法一
	@Test
	public void One() {
		// 获得资源包
		ResourceBundle bundle = ResourceBundle.getBundle("test");
		// 通过资源包拿到所有的名称
		Enumeration<String> allName = bundle.getKeys();
		// 遍历
		while (allName.hasMoreElements()) {
			// 获取每一个名称
			String name = (String) allName.nextElement();
			// 利用已得到的名称通过资源包获得相应的值
			String value = bundle.getString(name);
			System.out.println(name + "=" + value);
		}
	}

	// 方法二
	@Test
	public void Two() throws Exception {
		// 获得类加载器,然后把文件作为一个流获取
		InputStream in = ReadProperties.class.getClassLoader()
				.getResourceAsStream("test.properties");
		// 创建Properties实例
		Properties prop = new Properties();
		// 将Properties和流关联
		prop.load(in);
		// 获取所有的名称
		Enumeration<?> allName = prop.propertyNames();
		// 遍历
		while (allName.hasMoreElements()) {
			// 获得每一个名称
			String name = (String) allName.nextElement();
			// 利用已得到的名称通过Properties对象获得相应的值
			String value = (String) prop.get(name);
			System.out.println(name + "=" + value);
		}
		// 关闭资源
		in.close();
	}
}


测试二

public class PropertyMgr {
	static Properties props = new Properties();
	
	static {
		try {
			props.load(PropertyMgr.class.getClassLoader().getResourceAsStream("config/tank.properties"));
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
	
	private PropertyMgr() {};
	
	public static String getProperty(String key) {
		return props.getProperty(key);
	}
}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值