1

I have create a dbConnection.properties file and placed it into WEB-INF. To read that file and connect to database I hava written a class as

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;

}

}

Its going into catch block. How can i read .properties file?

1 Answer 1

3

Place the properties file under src if you are using eclipse or WEB-INF/classes if you are using ant or gradle or any other tool for that matter and then modify the statement

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

with

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

Make this changes and it will work!

Sign up to request clarification or add additional context in comments.

4 Comments

its giving fileNotFoundException
did you place the properties file under src folder? If you are using ant or any other tool like gradle to build then place the properties file under WEB-INF/classes and try
I have two packges under src. so the package which includes DBConnection class,I have placed this file into prjct.db package.
@Sonam Are you using eclipse? if so copy the properties file and then right click on src and then paste the file!! That is all you need to do. I will update the answer so that it would be more clear to you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.