Reputation: 1937
I have two Maven projects in Netbeans, com.foo.bar and com.foo.baz.
com.foo.bar is a dependency of com.foo.baz.
bar
+-src
| +-main
| +-java
| | +-com
| | +-foo
| | +-bar
| | +-App.java
| +-resources
| +-com
| +-foo
| +-bar
| +-config.properties
+-target
| +-classes
| +-com
| +-foo
| +-bar
| +-App.class
| +-config.properties
+-pom.xml
When, in Netbeans, I click to expand project baz->dependencies->bar->com.foo.bar, I see same contents as bar/target/classes/com/foo/bar. All good, I think.
com.foo.bar has the lines
// print current directory
System.out.println(new File(".").getAbsolutePath());
// load config files
Properties conf = new Properties();
conf.load(new FileInputStream(config.properties));
com.foo.baz is similar, but with nothing in resources/
. When I build-with-dependencies com.foo.bar and com.foo.baz and then run com.foo.baz, I get
/home/user/NetBeansProjects/baz/.
java.io.FileNotFoundException: config.properties (No such file or directory)
Is this a problem with the classpath, or what? Shouldn't Maven be handling this?
Upvotes: 1
Views: 1287
Reputation: 48055
If you want to load the config.properties
from the App
class then you can do it like this:
public class App {
public void someMethod() {
InputStream is = getClass().getResourceAsStream("config.properties");
Properties properties = new Properties();
try {
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("foo = " + properties.getProperty("foo"));
}
public static void main(String[] args) {
App app = new App();
app.someMethod();
}
}
The config.properties
is relative to the class that is used with getResourceAsStream()
.
Upvotes: 1
Reputation: 81902
You need to add the whole path to the file, like so
conf.load(new FileInputStream("com/foo/bar/config.properties"));
If you placed the file in the root folder inside resources, it'd work without the path.
bar
+-src
| +-main
| +-java
| | +-com
| | +-foo
| | +-bar
| | +-App.java
| +-resources
| +-config.properties
(...)
Upvotes: 0