packagecom.common.util.resource;importjava.io.BufferedInputStream;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.InputStream;importjava.io.UnsupportedEncodingException;importjava.util.HashMap;importjava.util.Map;importjava.util.Properties;importjava.util.ResourceBundle;/*** 资源文件工具类
* 1、建议把资源文件统一放置在 src/main/resource 路径下,如果要区别对待,可以在该路径下添加包
* 2、资源文件的路径写相对于 src/main/resource 的路径,文件名不包含文件后缀
* 3、ResourceBundle解析中文乱码,先安装 Properties Editor插件,然后参考getValue(String key)方法处理
*@authorliuguangping
**/
public classResourceUtil {privateResourceBundle resourceBundle;/*** 私有方法获取资源文件
*@paramresource:文件放到resource路径下面,文件名不需要文件类型(.properties)*/
privateResourceUtil(String resource){
resourceBundle=ResourceBundle.getBundle(resource);
}/*** 获取ResourceUtil对象
*@paramresource
*@return
*/
public staticResourceUtil getResourceUtil(String resource){return newResourceUtil(resource);
}/*** 根据key获取值:先通过ResourceUtil.getResourceUtil(resource)方法获取ResourceBundle对象
*@paramkey
*@return
*/
publicString getValue(String key){try{return new String(resourceBundle.getString(key).getBytes("ISO-8859-1"),"UTF-8");
}catch(UnsupportedEncodingException e) {
e.printStackTrace();return null;
}
}/*** 获取资源文件所有key-value值:需先初始化ResourceUtil对象
*@return
*/
public MapgetMap(){
Map map = new HashMap();try{for(String key:resourceBundle.keySet()){
map.put(key, resourceBundle.getString(key));
}
}catch(Exception e) {
e.printStackTrace();return null;
}returnmap;
}/*** 修改properties文件的值,功能未实现,功能待完善
*@paramresource
*@paramkey
*@paramvalue*/
public static voidupdateValue(String resource,String key,String value){
Properties pro= newProperties();
InputStream in= null;try{//
String filePath = ResourceUtil.class.getResource(resource).getFile();
System.out.println(filePath);//in = ResourceUtil.class.getResourceAsStream(filePath);
in = new BufferedInputStream(newFileInputStream(filePath));
pro.load(in);
FileOutputStream out= newFileOutputStream(filePath);
pro.put(key, value);
pro.store(out,"配置文件修改");
}catch(Exception e) {
e.printStackTrace();
}
}}