Java 项目:属性 资源目录中的文件不可访问

Java project: Property file from resource directory is not accessible

我正在构建一个 jersey-2 webapp。我无法从资源访问 config.property 文件。我错过了什么?

@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 初始化失败并出现以下错误:

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

你可以尝试 YourCurrentClass.class.getClassLoader().getResourceAsStream("config.properties")

主要区别在于,在 ClassLoader 实例上使用 getResourceAsStream 时,路径被视为从类路径的根开始的绝对路径。 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