How to get a context path of a properties file from a webservice in java?

Just another programmer picture Just another programmer · Mar 12, 2011 · Viewed 7.3k times · Source

I am trying read the context path of a properties file from my application,

properties.load(this.getClass().getResourceAsStream(path));



import java.util.Properties;

public class test1 {

    public String getValues()
    {
        PropertiesFileReader fileReader = new PropertiesFileReader();

        Properties prop = fileReader.getProp("/messages/AttachFile.properties");

        String out = prop.getProperty("FILE_NAME");

        return out;
    }
}

This works when the properties file is under WEB-INF -> classes -> messages -> myfile but when i move this file to some other folder like WEB-INF -> messages -> myfile it doesn't seem to get the path...

EDIT: I am not using servlets...

Answer

BalusC picture BalusC · Mar 12, 2011

If fails because the new path is not part of the classpath while Class#getResourceAsStream() loads resources from the classpath. The /WEB-INF/classes is by default part of the classpath as specified in the Servlet API specification, that's why it worked. I recommend to keep it in the classpath or to add the new path /WEB-INF/resources to the classpath.

If you're using an IDE like Eclipse, then you can do it by adding it as Source Folder in project's build path (which would during build move it back into the /WEB-INF/classes anyway). Alternatively, you can also just create a resources package in the Java source root and then put the file there. It will become part of the classpath as well.