首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java项目:无法访问资源目录中的属性文件

Java项目:无法访问资源目录中的属性文件
EN

Stack Overflow用户
提问于 2020-06-26 12:24:43
回答 2查看 32关注 0票数 1

我正在构建一个jersey-2网络应用程序。我无法从资源访问config.property文件。我遗漏了什么?

代码语言:javascript
复制
@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初始化失败,错误如下:

代码语言:javascript
复制
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)
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-06-26 12:28:53

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

票数 1
EN

Stack Overflow用户

发布于 2020-06-26 15:13:27

主要区别在于,在ClassLoader实例上使用getResourceAsStream时,从类路径的根开始将路径视为绝对路径。reading-file-in-java

代码语言:javascript
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62588011

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档