0

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)
sahoo1989
  • 21
  • 2
  • 6

3 Answers3

3

use ServletContext to access your web resources not the class loader

http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#getResourceAsStream(java.lang.String)

servletContext.getResourceAsString("/WEB-INF/resource/my.properties");
Dapeng
  • 1,704
  • 13
  • 25
0

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.

Gemtastic
  • 6,253
  • 6
  • 34
  • 53
0

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.");
        }
    }
}
Yan Khonski
  • 12,225
  • 15
  • 76
  • 114