3

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...

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

3 Answers3

2

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.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
0

you just have to prepend /WEB-INF/:

"/WEB-INF/messages/myfile";
bluefoot
  • 10,220
  • 11
  • 43
  • 56
0

When you say that you are not using servlets, what do you mean? How this code runs?
Basically, when you do use servlets, only WEB-INF/classes and WEB-INF/lib are on the classpath. So you cannot access the resources using classloaders. BUT you can access them using the ServletContext. So assuming your code runs in Servlet/JSP, you can do the following:

getServletContext().getResourceAsStream("your resource starting from web-application root");
Tarlog
  • 10,024
  • 2
  • 43
  • 67