package com.demo.test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.Properties;
import java.util.ResourceBundle;
/**
*
* 类: PropertiesUtil
* 描述: 读取配置文件
* 作者: xxx
* 版本: 1.0
* 时间: 2015-7-18 上午11:30:01
*/
public class PropertiesUtil { private ResourceBundle resourceBundle; private String Path; private Properties propertie; private InputStream inputStream; /*//不同包下通过Properties读取 String valueString1=new PropertiesUtil("/com/demo/config/config.properties").getPropertyValue("username"); System.out.println(valueString1); //当前包下读取 String valueString2=new PropertiesUtil("config.properties").getPropertyValue("username"); System.out.println(valueString2); String valueString3=new PropertiesUtil("com/demo/config/config",Locale.getDefault()).getProperty("username"); System.out.println(valueString3); */ /** * Path文件路径 * * @param Path * (Path示例:com/demo/config/config) */ public PropertiesUtil(String Path, Locale Locale1) { this.resourceBundle = ResourceBundle.getBundle(Path, Locale1.getDefault()); } /** * * @param Path1 (读取当前包下配置文件:config.properties) * Path2(读取不同包下配置文件:/com/demo/config/config.properties) */ public PropertiesUtil(String Path) { this.Path = Path; } /** * 通过Properties方式读取 通过对应key获取相对应value值 * * @param key键值 * @return value值 */ public String getPropertyValue(String key) { String result = ""; try { if (key == null || "".equals(key) || "null".equals(key)) { return ""; } propertie = new Properties(); inputStream = PropertiesUtil.class.getResourceAsStream(Path); propertie.load(inputStream); inputStream.close(); result = (String) propertie.getProperty(key); } catch (IOException e) { e.printStackTrace(); } return result; } /** * 通过ResourceBundle方式读取 通过对应key获取相对应value值 * * @param key键值 * @return value值 */ public String getProperty(String key) { if (key == null || "".equals(key) || "null".equals(key)) { return ""; } String result = ""; try { result = resourceBundle.getString(key); } catch (MissingResourceException e) { e.printStackTrace(); } return result; } }