giri
giri

Reputation: 27199

How to parse property value in properties file

Hi I am loading a property file to establish DB connection, ex:

DB1="JDBc................", username , password

above line is as in property file, but when i call getConnection method I need to send url, username and pw. How can I parse it.

Upvotes: 2

Views: 18847

Answers (3)

Nivas
Nivas

Reputation: 18344

  1. You can split the entry:

    String dbProperty = prop.getProperty("DB1");   
    String[] dbDetails = dbProperty.split(",", 3);
    

dbDetails[0] will hold your JDBC..., [1] your username and [2] your password

  1. Better still, you might want to hold them in different properties (As lweller said)

    db.username = scott  
    db.password = tiger  
    db.url = ....
    

This way you get better clarity and control.

Upvotes: 1

ChadNC
ChadNC

Reputation: 2503

You can put your key/value pairs in a properties file like this:

dbUrl = yourURL
username = yourusername
password = yourpassword

Then you can load them into your app from the properties file:

private void loadProps() {
    try {
        InputStream is = getClass().getResourceAsStream("database_props.properties");
        props = new Properties();
        props.load(is);
        is.close();
        dbConnStr = props.getProperty("dbUrl");
        username = props.getProperty("username");
        password = props.getProperty("password");
    }
    catch(IOException ioe) {
        log.error("IOException in loadProps");
        for(StackTraceElement ste : ioe.getStackTrace())
        log.error(ste.toString());
    }
}

And then you can use those values to create your connection.

Upvotes: 10

fmucar
fmucar

Reputation: 14548

It is better to define separately

dburl =....
username =....
password = ...

Still if you want to parse it, you can use the split method of string to split by comma

Upvotes: 0

Related Questions