Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properties getProperty returning null

Tags:

java

I'm having the following problem. I'm using Java properties to read some info of a file, but when I call prop.getProperty("var") it returns null. I ran out of ideas. Here is the code I have.

static final Properties prop = new Properties();
public JConnection(){
    try{
        prop.load(new FileInputStream("db.properties"));
    }catch(Exception e){
        logger.info("file not found.");
        e.printStackTrace();
    }
}

I never get the error message "file not found".

 public static Connection getConnection(String conType) {
    Connection conn;
    try {
        Class.forName("oracle.jdbc.driver.OracleDriver"); 
        if(model == "client"){
             conn = DriverManager.getConnection(prop.getProperty("url"),prop.getProperty("usr"),prop.getProperty("pass"));  
        }else{
            conn = DriverManager.getConnection(prop.getProperty("url1"),prop.getProperty("usr1"),prop.getProperty("pass1")); 
        }
    } catch (Exception ex) {            
        ex.printStackTrace();
        conn = null;
    }

When it tries to connect to the DB, getProperty is returning null as it is not found. Any ideas of what it could be or what I'm doing wrong?

like image 996
elcharrua Avatar asked Oct 22 '25 14:10

elcharrua


2 Answers

Another wild guess: I noticed that both your prop variable and the method that's reading from it are static, so maybe you are using this as some sort of static utilities class without ever creating an instance of the class? In this case, you are never calling the constructor and never actually loading the properties file. Instead, you might try this:

static final Properties prop = new Properties();
static {
    try{
        prop.load(new FileInputStream("db.properties"));
    }catch(Exception e){
        logger.info("file not found.");
        e.printStackTrace();
    }
}
like image 110
tobias_k Avatar answered Oct 25 '25 19:10

tobias_k


You have a static field (prop), but you initialize it in a constructor. This means if you consult your prop object before you construct any object of JConnection, prop will not be initialized.

You can try something like this:

public class JConecction {
    static final Properties prop = new Properties();

    static {
        try {
            prop.load(new FileInputStream("db.properties"));
        } catch(Exception e) {
            logger.info("file not found.");
            e.printStackTrace();
        }
    }
}
like image 27
angel_navarro Avatar answered Oct 25 '25 17:10

angel_navarro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!