Java – Can’t get the data from the properties file

javaproperties

Here's the class

package db;

import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Oshadha Gunawardena
 */
public class DBFacade {

    private static Connection c;

    public static void connect() throws Exception {
        if (c == null) {
            Properties prop = new Properties();
            FileInputStream fis = new FileInputStream("props.xml");
            prop.loadFromXML(fis);

            String dbUrl = prop.getProperty("dburl");
            String dbDriver = prop.getProperty("dbdriver");
            String dbUser = prop.getProperty("username");
            String dbPass = prop.getProperty("password");

            Class.forName(dbDriver).newInstance();

            c = DriverManager.getConnection(dbUrl, dbUser, dbPass);
        }
    }

    public static ResultSet fetch(String sql) throws Exception {
        connect();
        synchronized (c) {
            return c.createStatement().executeQuery(sql);
        }
    }

    public static void save(String sql) throws Exception {
        connect();
        synchronized (c) {
            c.createStatement().executeUpdate(sql);
        }
    }
}

I'm using this class as my database facade class,so my entire project is a web application I'm calling this fetch and save methods using a servlet, but when I try to run this It throws an exception (java.io.FileNotFoundException). All the paths are set correctly props.xml file is in my project home directory also it works when I try to print the data to the out put.

String dbUrl = prop.getProperty("dburl")
System.out.println(dbUrl);

Problem only occurs when I try to deploy and run the project.
Note: I'm using NetBeans 6.1 as my primary IDE.

Thanks

Best Solution

As J-16 SDiZ says, your file is probably ending up in the war file - or if it's not, then your working directory probably isn't what you think it is.

You say that props.xml is in the "project home directory" - where is it after deployment? Is it in a war file (in which case you'll need to use getResourceAsStream(), although I suspect that Class.getClassLoader().getResourceAsStream("props.xml") is more likely to work:

InputStream input = null;  
try
{
    input YourClassName.class.getClassLoader.getResourceAsStream("props.xml");
    if (input == null)
    {
         // Throw an appropriate exception here to show you can't find your file
    }
    prop.loadFromXML(input);
}
finally
{
    if (input != null)
    {
        input.close();
    }
}

If it really is a file, you'll need to find some way of working out the directory it's in programmatically, then use:

File file = new File(directory, "props.xml");
FileInputStream fis = new FileInputStream(file);
// And close it in a finally block as above