您的位置:首页 > 运维架构

一个读取properties的工具类!请大家多多指教!

2012-11-27 15:50 197 查看
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import org.apache.log4j.Logger;

/**
*
* Description:系统读取配置文件工具类
* All Rights Reserved.
* @version 1.0 2012-10-12 下午1:28:25 by albert(albertwxh@gmail.com)创建
*/
public class PropertiesUtil {
private static Logger logger = Logger.getLogger(PropertiesUtil.class);

public final static String CACHE_PROPERTIES_NAME = "cacheData";

/**
*
* Description:根据文件名称创建Properties对象
* @Version1.0 2012-10-12 下午1:31:30 by albert(albertwxh@gmail.com)创建
* @param propertiesName 资源文件名,推荐使用PropertiesUtil类的静态常量
* @return Properties对象
*/
public static Properties getProperties(String propertiesName){
String propertiesPath = getConfigPath(propertiesName);
return createProperties(propertiesPath);
}

/**
*
* Description: 获取Properties文件路径
* @Version1.0 2012-10-12 下午1:33:04 by albert(albertwxh@gmail.com)创建
* @param propertiesName 资源文件名,推荐使用PropertiesUtil类的静态常量
* @return 文件路径
*/
private static String getConfigPath(String propertiesName){
String resultPath = null ;
String classPath = PropertiesUtil.class.getClassLoader().getResource(PropertiesUtil.class.getName().replace('.', '/')+".class").getFile();
String classRoot = "";
classRoot = classPath.substring(0,classPath.indexOf("/com/common/util"));
if(!classRoot.equals("") && classRoot.startsWith("/") && classRoot.indexOf(":") == 2){
classRoot = classRoot.substring(1);
}
if(!classRoot.equals("")){
resultPath = classRoot+"/"+propertiesName+".properties";
}
return resultPath;
}
/**
*
* Description: 内部方法,根据Properties文件路径创建Properties对象
* @Version1.0 2012-10-12 下午1:40:55 by albert(albertwxh@gmail.com)创建
* @param fileFullName
* @return Properties对象
*/
private static Properties createProperties(String fileFullName){
try {
File file = new File(fileFullName);
FileInputStream fis = null ;
Properties properties = new Properties();
fis = new FileInputStream(file);
properties.load(fis);
return properties;
}catch (FileNotFoundException e) {
logger.error("系统读取Properties文件发生异常",e);
return null ;
}catch(IOException e){
logger.error("系统读取配置文件加载Properties对象时发生异常",e);
return null;
}
}
}

希望大家指教!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: