从添加到部署在 Tomcat 下的解压 WAR 中的 jar 读取外部属性文件

问题描述 投票:0回答:1

我正在尝试从 JAR 访问一个简单的 .properties 文件,该 JAR 添加到 Apache Tomcat 中解压的 .war 文件中。这是我到目前为止尝试过的方法:

InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("../classes/testProps.properties");
Properties props = new Properties();
props.load(inputStream);
System.out.println(props.get("test"));

但这并不能解决问题,因为我在输入流上不断收到

null

对于上下文,我需要将属性文件放在 WEB-INF/classes 文件夹下,并将 jar 文件放在 WEB-INF/lib 中。

java tomcat jar
1个回答
0
投票

这是您加载和读取外部文件属性的方式:

import java.io.InputStream;
import java.util.Properties;

InputStream inputStream = getClass().getClassLoader().getResourceAsStream("/custom.properties");
Properties customProperties = new Properties();
try {
    customProperties.load(inputStream);
} catch (IOException e) {
    e.printStackTrace();
    logger.error("IOException caught while reading properties file: " + e.getMessage());
}

if( customProperties.get("prop1") != null )
    boolean prop1 = Boolean.parseBoolean((String) customProperties.get("prop1"));
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.