Kuldeep Yadav
Kuldeep Yadav

Reputation: 1806

Java project: Property file from resource directory is not accessible

I am building a jersey-2 webapp. I can't access config.property file from resource. What am I missing?

@Bean(name = com.tarkshala.photo.drive.Configuration.CONFIGURATION_BEAN_NAME)
public Properties getConfiguration() throws IOException {
    Properties properties = new Properties();
    InputStream input = new FileInputStream("config.properties");
    properties.load(input);
    return properties;
}

Bean initialization fails with following error:

Caused by: java.lang.NullPointerException
    at com.tarkshala.photo.spring.SpringAppConfig.getConfiguration(SpringAppConfig.java:47)
    at com.tarkshala.photo.spring.SpringAppConfig$$EnhancerBySpringCGLIB$$3ecfb6f6.CGLIB$getConfiguration$5(<generated>)
    at com.tarkshala.photo.spring.SpringAppConfig$$EnhancerBySpringCGLIB$$3ecfb6f6$$FastClassBySpringCGLIB$$45328ae1.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358)

Upvotes: 1

Views: 45

Answers (2)

0gam
0gam

Reputation: 1423

The main difference is that when using the getResourceAsStream on a ClassLoader instance, the path is treated as absolute starting from the root of the classpath. reading-file-in-java

public InputStream getResourceFileAsInputStream(String fileName) {
    ClassLoader classloader = SpringAppConfig.class.getClassLoader();
    return classloader.getResourceAsStream(fileName);   
}

public Properties getConfiguration() throws IOException {
    Properties properties = new Properties();
    InputStream input = getResourceFileAsInputStream("config.properties");
    properties.load(input);

    return properties;
} 

java-properties-file-examples

Upvotes: 1

Dega ASHOK KUMAR
Dega ASHOK KUMAR

Reputation: 36

You can try YourCurrentClass.class.getClassLoader().getResourceAsStream("config.properties")

Upvotes: 1

Related Questions