读取 .properties 文件有 4 种方式,下面我们给出源码。
测试代码目录结构
测试代码目录结构
config.properties 文件
time=2020-09-16 08:21:52
name=\u6d4b\u8bd5\u8bfb\u53d6\u0020\u002e\u0070\u0072\u006f\u0070\u0065\u0072\u0074\u0069\u0065\u0073\u0020\u6587\u4ef6
1. 基于ClassLoder读取配置文件
Test1.java
package code;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Test1 {
public static void main(String[] args) {
Properties properties = new Properties();
// 使用ClassLoader加载properties配置文件生成对应的输入流
InputStream in = Test1.class.getClassLoader().getResourceAsStream("conf/config.properties");
try {
// 使用properties对象加载输入流
properties.load(in);
//获取key对应的value值
String name = properties.getProperty("name");
System.out.println(name);
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. 基于 InputStream 读取配置文件
该方式的优点在于可以读取任意路径下的配置文件
Test2.java
package code;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
public class Test2 {
public static void main(String[] args) {
Properties properties = new Properties();
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader("../conf/config.properties"));
properties.load(bufferedReader);
//获取key对应的value值
String name = properties.getProperty("name");
System.out.println(name);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3. 通过 java.util.ResourceBundle.getBundle() 静态方法来获取
该方式来获取properties属性文件不需要加.properties后缀名,只需要文件名即可。
Test3.java
package code;
import java.util.ResourceBundle;
public class Test3 {
public static void main(String[] args) {
ResourceBundle resource = ResourceBundle.getBundle("conf/config");
String name = resource.getString("name");
System.out.println(name);
}
}
4. 使用 PropertyResourceBundle 类读取
Test4.java
package code;
import java.io.IOException;
import java.io.InputStream;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
public class Test4 {
public static void main(String[] args) {
// 使用ClassLoader加载properties配置文件生成对应的输入流
InputStream in = Test4.class.getClassLoader().getResourceAsStream("conf/config.properties");
try {
ResourceBundle resource = new PropertyResourceBundle(in);
String name = resource.getString("name");
System.out.println(name);
} catch (IOException e) {
e.printStackTrace();
}
}
}