您的位置:首页 > 编程语言 > Java开发

Java读取.properties资源文件的常用2种方法

2013-04-07 15:39 776 查看
在Java项目开发中,经常需要读取.properties资源类型资源文件。例如数据库配置文件,spring配置文件,用户自定义配置文件等待。下面简单分享自己常用的2中Java读取配置文件的方法:

1、使用ResourceBundle

public class Resources {

public static final Log LOG = LogFactory.getLog(Resources.class.getName());

private static final String PREFIX = "conf."; //包名称
private ResourceBundle resource;

public Resources(String fileName){
try {
resource = ResourceBundle.getBundle(PREFIX + fileName, Locale.getDefault()); //eg. conf/mysql.properties
} catch (MissingResourceException e) {
// TODO: handle exception
e.printStackTrace();
}
}

public String get(String key){
String ret = null;
ret = resource.getString(key);
if(ret == null){
LOG.error("key : "+key +" not existed or value of the key is null");
}
return ret.trim();
}
}


2、使用Properties

public class Resources {

private Properties pro;

public Resources() throws IOException{
FileInputStream  in = new FileInputStream("mysql.properties");
pro = new Properties();
pro.load(in);
in.close();
}

public String get(String key){
return pro.getProperty(key);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: