Friday, February 17, 2012

How to Read Property file using Java - Get Database connection parameters from property file

7 comments
  • Here is the java class to read property file which will help to create database connection. 







package jsupport.com.db;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

/**
 *
 * @author JSupport http://javasrilankansupport.blogspot.com/
 */
public class ReadPropertyFile {

    public static String db_driver;
    public static String db_url;
    public static String db_username;
    public static String db_password;

    static {
        try {
            Properties prop = new Properties();
            prop.load(new FileInputStream("Config.properties"));

            String driver = prop.getProperty("db_driver");
            String ip = prop.getProperty("db_ip");
            String dbName = prop.getProperty("db_name");

            db_username = prop.getProperty("db_username");
            db_password = prop.getProperty("db_password");

            if (driver.equals("SQL2000")) {
                db_driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
                db_url = "jdbc:microsoft:sqlserver://" + ip + ":1433;DatabaseName=" + dbName;
            } else if (driver.equals("SQL2005")) {
                db_driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
                db_url = "jdbc:sqlserver://" + ip + ":1433;databaseName=" + dbName;
            } else if (driver.equals("MySQL")) {
                db_driver = "com.mysql.jdbc.Driver";
                db_url = "jdbc:mysql://" + ip + ":3306/" + dbName;
            }

            System.out.println("Database Driver :"+db_driver+ " Database URL :"+db_url);

        } catch (IOException ex) {
            System.out.println("Can not read property file...");
        }
    }
}




  • Create Config.properties under your source code package and add following properties 


Config.properties


# JSupport http://javasrilankansupport.blogspot.com/

#databace properties
#db_driver=SQL2000
#db_driver=SQL2005
db_driver=MySQL
db_ip=localhost
db_name=mysql
db_username=root
db_password=123

7 comments:

Anonymous said...

gud........

Dev said...

Thank you

ArpitSen said...

Hi,

I thought it would be a good addition from the link below. The article talks about other ways to load the property file and also tells the side-effect of those ways.

http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html

Munsey said...

You didn't close your FileInputStream.

Jay said...

It is good idea to use finally to close FileInputStream

javin paul said...

if you don't close your files properly your program may run out of available file descriptor and you won't be able to open any more files. by the I have also blogged about How to read from text file in java let me know how do you find it.

Java-Only said...

How to read properties from .properties file

Post a Comment