加载properties文件的三种方法

时间:2023-03-08 17:55:28
加载properties文件的三种方法

源代码:

package a.one;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties; public class Test1 {
/* private static String driver;
private static String url;
private static String user;
private static String password;*/ //利用反射加载properties文件
public static void main(String[] args) throws Exception {
//
Properties p=new Properties();
FileInputStream in=new FileInputStream("config/c.properties");
p.load(in);
System.out.println(p);
System.out.println("name:"+p.getProperty("name"));
System.out.println("============使用类加载器加载properties文件=============");
InputStream in2=Test1.class.getClassLoader().getResourceAsStream("db.properties");
Properties p2=new Properties();
p2.load(in2);
System.out.println(p2);
System.out.println("password:"+p2.getProperty("password"));
System.out.println("============直接用类文件加载,其实里面就是封装了getClassLoader()方法==============");
InputStream in3=Test1.class.getResourceAsStream("/db.properties");
Properties p3=new Properties();
p3.load(in3);
System.out.println(p3);
System.out.println("user:"+p3.getProperty("user"));
}
}

配置文件db.properties在src下

 driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydb3
user=root
password=123456

结果:

{age=30, name=taeyeon, song=four seasons}
name:taeyeon
============使用类加载器加载properties文件=============
{user=root, password=123456, url=jdbc:mysql://localhost:3306/mydb3, driver=com.mysql.jdbc.Driver}
password:123456
============直接用类文件加载,其实里面就是封装了getClassLoader()方法==============
{user=root, password=123456, url=jdbc:mysql://localhost:3306/mydb3, driver=com.mysql.jdbc.Driver}
user:root