I have Manven project in IntelijWorkspace, in the /resources
folder, I add a .properties
file called SBMessages.properties
. Now, I tried to get this file from Java, it always throws FileNotFoundException
.
Below is my project's tree:
And my code to get the .properties file in SBConnector.class:
public void initialize() {
SBMessages = new Properties();
try {
SBMessages.load(getClass().getResourceAsStream("/sb/elements/SBMessages.properties"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Try to debug, the path direct to /target/classes/elements/SBMessages.properties
instead of /resources/sb/elements/SBMessages.properties.
Please help me to fix this problem.
Different frameworks provide different class loaders. You probably have the "default" class loader from the JRE you're using. It will follow the JDK documentation. You might fall across this page: http://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html#getResource(java.lang.String) but the more helpful page is this one: http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String) which actually says that you can start your resource name with a slash.
Despite this documentation, your class loader may not be following these rules. How disappointing. So, there are three forms to try:
In addition to these three forms, you also have to call the getResourceAsStream() on the right class. The class ought to be in the same jar file as the one holding your properties file. This can be confusing, so its a good thing you started with a simple example. :-)
Works for me like this:
public static void main(String[] args) {
new NewMain().doit();
}
public void doit() {
Properties prop = new Properties();
try (InputStream inputStream = NewMain.class.getResourceAsStream("/data/newproperties.properties")) {
prop.load(inputStream);
System.out.println("hello " + prop.getProperty("x", "default"));
} catch (FileNotFoundException e) {
e.printStackTrace(System.out);
} catch (IOException e) {
e.printStackTrace(System.out);
}
}
So you are not using the standard directory layout, hopefully for a good reason, otherwise I advise you to do so.
Right now your /resources
folder is not recognized as a folder which needs to be added to the classpath. (You can confirm this by seeing that /target/classes/sb/elements/SBMessages.properties
doesn't exists) You could configure it as describes by http://maven.apache.org/pom.html#Resources but again it is probably for everybody better to stick to the default directory layout, it reduces the configuration a lot.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With