import java.util.ResourceBundle;
/**
* 用来测试获取配置文件的类
* @author BaiKeyang
*
*/
public class ResourceUtils {
public static String getValue(String file, String key) {
String value;
// 未取到值,从properites文件中查找
try {
ResourceBundle bundle = ResourceBundle.getBundle(file);
value = bundle.getString(key);
if (value==null){
throw new RuntimeException("没有该属性的值:"+key);
}
value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
return value;
} catch (Throwable e) {
System.err.println(e);
return null;
}
}
public static void main(String[] args) {
String resourceFile = "config.dataBase";
// 创建一个默认的ResourceBundle对象
// ResourceBundle会查找包config下的dataBase.properties的文件
// config是资源的包名,它跟普通java类的命名规则完全一样:
// - 区分大小写
// - 扩展名 .properties 省略。就像对于类可以省略掉 .class扩展名一样
// - 资源文件必须位于指定包的路径之下(位于所指定的classpath中)
// 假如你是在非Web项目中使用,则一定要写资源文件的路径,也就是包路径必须存在。
// 如果是Web项目,不写包路径可以,此时将资源文件放在WEB-INF\classes\目录下就可以。
String url = getValue(resourceFile, "db.url");
System.out.println(url);
}
}
/**
* 用来测试获取配置文件的类
* @author BaiKeyang
*
*/
public class ResourceUtils {
public static String getValue(String file, String key) {
String value;
// 未取到值,从properites文件中查找
try {
ResourceBundle bundle = ResourceBundle.getBundle(file);
value = bundle.getString(key);
if (value==null){
throw new RuntimeException("没有该属性的值:"+key);
}
value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
return value;
} catch (Throwable e) {
System.err.println(e);
return null;
}
}
public static void main(String[] args) {
String resourceFile = "config.dataBase";
// 创建一个默认的ResourceBundle对象
// ResourceBundle会查找包config下的dataBase.properties的文件
// config是资源的包名,它跟普通java类的命名规则完全一样:
// - 区分大小写
// - 扩展名 .properties 省略。就像对于类可以省略掉 .class扩展名一样
// - 资源文件必须位于指定包的路径之下(位于所指定的classpath中)
// 假如你是在非Web项目中使用,则一定要写资源文件的路径,也就是包路径必须存在。
// 如果是Web项目,不写包路径可以,此时将资源文件放在WEB-INF\classes\目录下就可以。
String url = getValue(resourceFile, "db.url");
System.out.println(url);
}
}