目录结构:
背景:如上面的目录结构所示,现在要在JavaGetProperties.java中读取config.properties文件
config.properties
userPassword=123456
1、方法一(利用Properties中load()读取properties文件)
@Test
public void test1() {
Properties prop = new Properties();
try {
prop.load(new FileInputStream("src/config/config.properties"));
System.out.println(prop.getProperty("userPassword"));
} catch (IOException e) {
e.printStackTrace();
}
}
2、方法二(利用Properties中load()读取properties文件)
@Test
public void test2() {
Properties prop = new Properties();
try {
InputStream in = this.getClass().getClassLoader().getResourceAsStream("config/config.properties");
prop.load(in);
System.out.println(prop.getProperty("userPassword"));
} catch (IOException e) {
e.printStackTrace();
}
}
3、方法三(利用Properties中load()读取properties文件)
@Test
public void test3() {
Properties prop = new Properties();
try {
InputStream in = JavaGetProperties.class.getClassLoader().getResourceAsStream("config/config.properties");
prop.load(in);
System.out.println(prop.getProperty("userPassword"));
} catch (IOException e) {
e.printStackTrace();
}
}
4、方法四 (利用ResourceBundle读取properties文件)
@Test
public void test4() {
try {
InputStream in = JavaGetProperties.class.getClassLoader().getResourceAsStream("config/config.properties");
ResourceBundle rb = new PropertyResourceBundle(in);
System.out.println(rb.getString("userPassword"));
} catch (IOException e) {
e.printStackTrace();
}
}
5、方法五(利用ResourceBundle.getBundle()读取properties文件)
@Test
public void test5() {
// 不需要加.properties后缀名
ResourceBundle bundle = ResourceBundle.getBundle("config/config");
String s = bundle.getString("userPassword");
System.out.println(s);
}
6、方法六(当类和属性文件在同一个文件夹下)
@Test
public void test6() {
Properties prop = new Properties();
try {
InputStream in = JavaGetProperties.class.getResourceAsStream("config.properties");
prop.load(in);
System.out.println(prop.getProperty("userPassword"));
} catch (IOException e) {
e.printStackTrace();
}
}
7、方法七(使用class.getClassLoader()所得到的java.lang.ClassLoader的getResourceAsStream()方法)
@Test
public void test7() {
Properties prop = new Properties();
try {
InputStream in = ClassLoader.getSystemResourceAsStream("config/config.properties");
prop.load(in);
System.out.println(prop.getProperty("userPassword"));
} catch (IOException e) {
e.printStackTrace();
}
}