Search code examples
javapathrelative-path

Relative path on JAR file used in a web application


I have a Java application (non-web) which must read from a properties file. This Java application must as well be exported as a JAR file and then is used in a web application, but the properties file is not into the JAR file. It would look like this:

/webapps/MyWebApp/WEB-INF/myJavaApp.jar
/webapps/MyWebApp/WEB-INF/config.properties

So, when coding the Java application that will be exported as myJavaApp.jar I am unable to do it so it would read the config.properties file from a Relative path. If I put an Absolute path it works correctly:

properties.load(new FileInputStream("C:/Program Files/Apache Software Foundation/Tomcat 6.0/webapps/MyWebApp/WEB-INF/config.properties"));

But, if I try to use a relative path it doesn't work. I've tried different solutions from here or other webpages but none of them are working.

Almost forgot, the class where I am reading the properties file is static!


Solution

  • If you make sure the file is on the classpath, then you can simply load it with YourClassName.class.getResourceAsStream("/config.properties"). That would be the easiest way of implementing it. For your webapplication, you put the file in WEB-INF/classes/, and for your standalone application you simply set the classpath when starting the application.