1.通过字节码文件的类加载器的字节流读取文件。
@Test
public void f1() throws Exception{ //通过字节流文件获取jdbc连接 InputStream is = Demo1.class.getClassLoader().getResourceAsStream("jdbc.properties"); Properties pr = new Properties(); pr.load(is);
     //通过键获取值 String driverClass
= pr.getProperty("driverClass"); String url = pr.getProperty("url"); String user = pr.getProperty("user"); String password=pr.getProperty("password"); Class.forName(driverClass); Connection conn = DriverManager.getConnection(url, user, password); is.close(); System.out.println(conn); }

2.通过字符输入流读取配置文件,文件的路径为绝对路径,放在项目名下可以直接写配置文件名字全称即可。

@Test
    public void f2() throws Exception{
        //通过字符流文件获取jdbc连接
        FileReader fr = new FileReader("../propeities/src/jdbc.properties");
        Properties pr = new Properties();
        pr.load(fr);
        String driverClass = pr.getProperty("driverClass");
        String url = pr.getProperty("url");
        String user = pr.getProperty("user");
        String password=pr.getProperty("password");
        
         Class.forName(driverClass);
            
         Connection conn = DriverManager.getConnection(url, user, password);
        fr.close();
         System.out.println(conn);
    }

3.通过ResourceBundle里的静态方法getBundle。

@Test
    public void f3() throws Exception{
        //
        ResourceBundle rb = ResourceBundle.getBundle("jdbc");
        String driverClass = rb.getString("driverClass");
        String url = rb.getString("url");
        String user = rb.getString("user");
        String password = rb.getString("password");
        Class.forName(driverClass);
        
        Connection conn = DriverManager.getConnection(url, user, password);
         System.out.println(conn);
    }

配置文件如下:

driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/store28 //store28为自己的数据库名字  localhost:3306/ 可以直接替换为/
user=root
password=123