mre
mre

Reputation: 44240

Reference properties file outside src directory

If I have the following directory structure,

+src
++com.foo.util
+++FooProperties.java
+foo.properties

How do I reference foo.properties as a resource stream in FooProperties? I've tried adding it to the classpath and referencing it as such,

FooProperties.class.getResourceAsStream("/foo.properties")

but I get a NullPointerException. What am I doing wrong?

Upvotes: 0

Views: 4097

Answers (1)

Rahul
Rahul

Reputation: 45040

If you want to keep the properties file outside the src(same level as src), then you can fetch your properties file this way:-

try {
    InputStream fileStream = new FileInputStream(new File(
            "test.properties"));
    Properties props = new Properties();
    props.load(fileStream);
    String myPropValue = (String) props.get("test.prop");
    System.out.println(myPropValue);
} catch (FileNotFoundException e) {
} catch (IOException e) {
}

Hope it helps. You can even edit the properties file using the above method(no absolute path required).

Upvotes: 3

Related Questions