在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);
}
}