java 读取properties文件

一、文件位置

properties文件内容:

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

二、代码

需要注意的是java工程的路径为srcconfig.properties,java web的路径为WEB-INFclassesconfig.properties 。部署的时候tomcat会将config.properties编译到WEB-INFclassesconfig.properties目录下。

所以如果在java web工程下仍然使用java工程的路径会无法获取到参数。

public class DBUtil {
   private static String driver = "";
    private static String url = "";
    private static String user = "";
    private static String password = "";
    private static boolean flag = false;
    /**
     * 加载JDBC连接数据库参数
     */
    public void getParm(){
        Properties p = new Properties();
        try {
            InputStream in =  this.getClass().getClassLoader().getResourceAsStream("config.properties");            
            p.load(in);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        driver = p.getProperty("driver");
        url = p.getProperty("url");
        user = p.getProperty("user");
        password = p.getProperty("password");
        flag = true;
    }
  public static Connection getConnection(){
    if(!flag){//每次连接的时候都看下加载了没
     DBUtil db = new DBUtil();
     db.getParm();
  }

}
原文地址:https://www.cnblogs.com/CryOnMyShoulder/p/8056100.html