1

我创建了一个 dbConnection.properties 文件并将其放入 WEB-INF。为了读取该文件并连接到数据库,我编写了一个类作为

public class DbConnection {

public static Connection connection()
{
    Connection con=null;
    //String connectionURL = "jdbc:mysql://localhost:3306/demo";
    try
    {
        Properties prop=new Properties();
        FileInputStream in = new FileInputStream(System.getProperty("WEB-INF/dbConnection.properties"));
        prop.load(in);
        in.close();

        String drivers = prop.getProperty("jdbc.drivers");
        String connectionURL = prop.getProperty("jdbc.url");
        String username = prop.getProperty("jdbc.username");
        String password = prop.getProperty("jdbc.password");

        //Class.forName("com.mysql.jdbc.Driver").newInstance();
        Class.forName(drivers);
        con=DriverManager.getConnection(connectionURL,username,password);

            System.out.println("Connection Successful");
            return con;     
    }
    catch(Exception e)
    {
        System.out.println("error !!");
    }
    return null;

}

}

它进入 catch 块。我如何读取 .properties 文件?

4

1 回答 1

3

src如果您正在使用 eclipse 或者WEB-INF/classes您正在使用 ant 或 gradle 或任何其他工具,请将属性文件放在下面,然后修改语句

 FileInputStream in = new FileInputStream(System.getProperty("WEB-INF/dbConnection.properties"));
        prop.load(in);

 prop.load(DbConnection.class.getClassLoader()
                    .getResourceAsStream("dbConnection.properties"));

进行此更改,它将起作用!

于 2012-07-18T05:36:53.503 回答