Java中使用getResourceAsStream加载Properties文件失败求助
问题排查与解决
出现NullPointerException是因为getResourceAsStream没找到指定的properties文件,返回了null。结合你的场景,按以下步骤排查:
1. 修正资源路径写法
你当前用的TestGraph.class.getResourceAsStream("oAuth.properties")是从当前类所在的包路径下去查找资源,而src/main/resources下的文件编译后会放在类路径的根目录,所以需要调整路径:
- 方法一:给路径加上前缀
/,表示从类路径根目录查找:
final Properties oAuthProperties = new Properties(); try { oAuthProperties.load(TestGraph.class.getResourceAsStream("/oAuth.properties")); } catch (IOException e) { System.err.println("Unable to read OAuth configuration: " + e.getMessage()); return; }
- 方法二:改用类加载器的
getResourceAsStream,它默认从类路径根目录查找,不需要前缀:
final Properties oAuthProperties = new Properties(); try { oAuthProperties.load(TestGraph.class.getClassLoader().getResourceAsStream("oAuth.properties")); } catch (IOException e) { System.err.println("Unable to read OAuth configuration: " + e.getMessage()); return; }
2. 确认编译后文件的实际位置
Spring Initializer创建的Maven/Gradle项目,编译后src/main/resources下的文件会被复制到:
- Maven:
target/classes目录 - Gradle:
build/classes/java/main目录
打开对应目录,确认oAuth.properties是否存在,同时检查文件名大小写(Linux/Mac系统严格区分大小写,比如实际是OAuth.properties和代码里的oAuth.properties会不匹配)。
3. 检查项目资源配置
确认pom.xml(Maven)或build.gradle(Gradle)没有修改默认资源配置,比如有没有排除src/main/resources目录,或者自定义了资源路径。正常Spring Initializer生成的配置不会有这个问题,但如果手动改过需要检查。
4. 多模块项目额外检查
如果是多模块项目,要确认当前模块的资源是否被正确打包到类路径中,或者有没有类加载器隔离导致无法读取其他模块资源的情况。
内容的提问来源于stack exchange,提问作者user2315104
相关产品推荐
相关产品推荐

