1、基于ClassLoder读取配置文件
注意:该方式只能读取类路径下的配置文件,有局限但是如果配置文件在类路径下比较方便。
InputStream inputStream1 = PropertiesTest.class.getResourceAsStream("filepath");
2、基于 InputStream 读取配置文件
注意:该方式的优点在于可以读取任意路径下的配置文件。
InputStream inputStream1 = new BufferedInputStream(new FileInputStream("filepath"));
3、举例:
(1)结构:
(2)代码
public class PropertiesUtil {
public static final PropertiesUtil INSTANCE = new PropertiesUtil();
public static PropertiesUtil getInstance(){
return INSTANCE;
}
/**
* 1.使用getResourceAsStream读取配置文件
*/
public void readPropertiesByGetSourceAsStream(){
// 1.src下面com/demo/config包内的配置文件config1.properties
InputStream inputStream1 = PropertiesTest.class.getClassLoader().getResourceAsStream("com/demo/config/config1.properties");
// 2.读取和PropertiesTest位于同一个包内的配置文件config2.properties
InputStream inputStream2 = PropertiesTest.class.getResourceAsStream("config2.properties");
// 3.读取src根目录下的配置文件config3.properties
InputStream inputStream3 = PropertiesTest.class.getClassLoader().getResourceAsStream("config3.properties");
// 4.读取位于另外一个resource文件夹里面的配置文件config4.properties
InputStream inputStream4 = PropertiesTest.class.getClassLoader().getResourceAsStream("config4.properties");
Properties properties = new Properties();
System.out.println("使用getResourceAsStream()配置文件...");
try {
System.out.println("-----读取inputStream1开始-----");
properties.load(inputStream1);
System.out.println("config1.properties:username = "+properties.getProperty("username") + ",password = " +properties.getProperty("password") +",url = " + properties.getProperty("url"));
System.out.println("-----读取inputStream1结束-----");
System.out.println("---------------------------------------------");
System.out.println("-----读取inputStream2开始-----");
properties.load(inputStream2);
System.out.println("config2.properties:username = "+properties.getProperty("username") + ",password = " +properties.getProperty("password") +