sgoldberg
sgoldberg

Reputation: 487

PropertiesConfiguration how to reference config.properties

I am new to Java so forgive me for my lack of knowledge. I am trying to utilize a properties file in my web app. While researching I found this article http://commons.apache.org/configuration/howto_properties.html which seemed pretty straight forward so I attempted to implement this. I attempted to implement as follows :

    Configuration config = new PropertiesConfiguration("stream.bundle.config"); 

I have tried stream.bundle.config, bundle.config and many other combinations but every time I get back an exception that says Cannot locate configuration source. The file is in a folder under src called bundle. My question is a) where should the file be? b) how should I reference it. I apologize for my lack of knowledge. Thanks in advance.

update:

I also tried

        FileInputStream in; 
    Properties p = new Properties();

    try{
        in  = new FileInputStream("config.properties");
        p.load(in);

    }
    catch(Exception e){
        System.out.println("Error: " + e);
    }

and I get java.io.FileNotFoundException: config.properties (The system cannot find the file specified) or java.io.FileNotFoundException: config (The system cannot find the file specified)

Upvotes: 1

Views: 9947

Answers (2)

sam
sam

Reputation: 11

Try this:

Properties properties = new Properties();
try 
{
    properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("xyz.properties"));
} 
catch (IOException e) 
{
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Upvotes: 1

hovanessyan
hovanessyan

Reputation: 31463

Regarding a) where should the file be:

  • in the current directory
  • in the user home directory
  • in the classpath

If you consider using Java's Properties you have to get an InputStream some way. If you're loading the properties from a class in the package, you have to use:

getClass().getResourceAsStream("resource.properties");

and if the class is in another package:

getClass().getResourceAsStream("some/pkg/resource.properties");

You can try loading the properties via the ClassLoader:

ClassLoader.getResourceAsStream ("some/pkg/resource.properties");

If you have a ServletContext, you can use:

ServletContext.getResourceAsStream(..)

EDIT: you should reference your file by the full name (filename+extension). So your first try should have been:

Configuration config = new PropertiesConfiguration("config.properties");

Upvotes: 2

Related Questions