首先创建一个properties配置文件:dbinfo.properties 供测试用。
内容为:
怎样获取age属性值?我们可以使用两种方法:
①使用反射的类加载器读取配置文件;
②使用工具类ResourceBundle
①反射的类加载器
public class ClassLoaderproper {
public static void main(String[] args) throws IOException {
//通过字节码获取类加载器
ClassLoader classLoader = ClassLoaderproper.class.getClassLoader();
//由类加载器读取配置文件获取输入流
InputStream is = classLoader.getResourceAsStream("dbinfo.properties");
//读取配置文件
Properties prop=new Properties();
//加载输入流
prop.load(is);
String age=prop.getProperty("age");
System.out.println(age);
}
}
②工具类ResourceBundle
public class ResourceBundleText {
public static void main(String[] args) {
ResourceBundle bundle = ResourceBundle.getBundle("dbinfo");
String age = bundle.getString("age");
System.out.println(age);
}
}
这样就可以获得properties配置文件里任意属性的值了。