Any suggestions to read properties file kept inside WEB-INF/resource using class loader. Something like :-
String fileName = "/WEB-INF/resource/my.properties";
InputStream input =MyClass.class.getClassLoader().getResourceAsStream(fileName);
properties = new Properties();
properties.load(input);
(Note- I don't want to read using servletcontext)
Find the error for above code:-
java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Unknown Source)
at java.util.Properties.load0(Unknown Source)
at java.util.Properties.load(Unknown Source)
use ServletContext to access your web resources not the class loader
servletContext.getResourceAsString("/WEB-INF/resource/my.properties");
When you're using getResourceAsStream()
you're defaulting into the resources folder. Unless your WEB-INF
is in the resources folder, it's won't find it because it doesn't exist.
If your source folder is src/main/com/mycompany/myapp/ and that's where web-inf is located, your path should be something like
String sourcePath = "../WEB-INF/resource/my.properties"
As you have to go back one folder (into the project root) and up into the WEB-INF folder.
I used this approach
public class HibernateConfig {
public static final Properties HIBERNATE_PROPERTIES = readProperties();
private static final String HIBERNATE_PROPERTIES_RESOURCE = "hibernate.properties";
private static Properties readProperties() {
try (BufferedInputStream is = new BufferedInputStream(ClassLoader.getSystemResourceAsStream(HIBERNATE_PROPERTIES_RESOURCE))) {
Properties properties = new Properties();
properties.load(is);
return properties;
} catch (IOException e) {
throw new RuntimeException("Failed to read properties from scr/properties.");
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.