javatomcatjar

Read external properties file from jar added to an unpacked WAR deployed under Tomcat


I'm trying to access a simple .properties file from a JAR that is added to an unpacked .war file in Apache Tomcat. This is the approach I tried so far:

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

But this doesn't do the trick as I keep getting a null on the inputStream.

For context, I need to put the properties file under the WEB-INF/classes folder and the jar file in WEB-INF/lib.


Solution

  • This is how you are able to load and read external file properties:

    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"));