获取工程下的Properties文件大体有2种方式,取决于你的properties文件是放在工程中的哪个位置,下面分别介绍如下:
1、在同一个包下,如果此时不在同一包下那么会报 null point Exception:
此时可以通过如下2种方式 代码获取:
@Test
public void getProperties(){
InputStream is = this.getClass().getResourceAsStream("/com/demo/c3p0/db.properties");
Properties p = new Properties();
try {
p.load(is);
String driver =p.getProperty("jdbcDriver");
String url =p.getProperty("jdbcUrl");
String userName =p.getProperty("jdbcUserName");
String passWord =p.getProperty("jdbcPassword");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void getProperties2(){
InputStream is = PropertiesUtils.class.getResourceAsStream("/com/demo/c3p0/db.properties");
Properties p = new Properties();
try {
p.load(is);
String driver =p.getProperty("jdbcDriver");
String url =p.getProperty("jdbcUrl");
String userName =p.getProperty("jdbcUserName");
String passWord =p.getProperty("jdbcPassword");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
2、在不同一包下,这种也是我们最常用的配置方式
此时通过如下代码获取:
在代码中getClassLoader()是通过类加载器获取类路径(clsasspath)下的文件
@Test
public void getProperties3(){
InputStream is = this.getClass().getClassLoader().getResourceAsStream("db.properties");
Properties p = new Properties();
try {
p.load(is);
String driver =p.getProperty("jdbcDriver");
String url =p.getProperty("jdbcUrl");
String userName =p.getProperty("jdbcUserName");
String passWord =p.getProperty("jdbcPassword");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}