You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tomcat下已解压WAR中JAR读取properties文件遇inputStream为null

问题解决:Tomcat中读取WEB-INF/classes下的properties文件

你的代码无法获取到输入流的核心原因是错误使用了相对路径../classes/:类加载器的getResourceAsStream方法是从类路径根目录开始查找资源的,而WEB-INF/classes本身就是Web应用的类路径根之一,不需要通过../向上跳转定位。

正确实现方式

方式1:通过类加载器直接加载

因为testProps.properties放在WEB-INF/classes下(即类路径根),直接使用文件名即可:

InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("testProps.properties");
Properties props = new Properties();
if (inputStream != null) {
    props.load(inputStream);
    System.out.println(props.get("test"));
    inputStream.close(); // 记得关闭流
}

如果properties文件在某个子包下(比如com/example/config),则路径要写成包结构的相对路径:

// 对应WEB-INF/classes/com/example/config/testProps.properties
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("com/example/config/testProps.properties");

方式2:通过ServletContext加载(Web环境专属)

如果是在Servlet、Filter等Web组件中,可以直接通过ServletContext访问Web应用目录下的资源,路径以/开头对应Web应用根目录:

// 假设在Servlet中,通过getServletContext()获取上下文对象
InputStream inputStream = getServletContext().getResourceAsStream("/WEB-INF/classes/testProps.properties");
Properties props = new Properties();
if (inputStream != null) {
    props.load(inputStream);
    System.out.println(props.get("test"));
    inputStream.close();
}

关键注意事项

  • 确认testProps.properties确实被部署到了WEB-INF/classes目录下:比如Maven项目中,要把文件放在src/main/resources目录下,构建时会自动复制到classes目录;
  • 绝对不要使用本地文件系统路径(比如C:/tomcat/webapps/xxx/WEB-INF/classes/...),这种写法依赖特定部署环境,不具备可移植性;
  • 必须添加非空判断,避免inputStream为null时调用load()抛出空指针异常。

内容的提问来源于stack exchange,提问作者Misone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 22:16:03