Question

I am writing webApp that use jsp file to call java class directly to get results.

The JSP file is like:

<%
    String queryKey = request.getParameter("id");
    int jobID = Integer.parseInt(queryKey);
    out.println(jobID);
    ArrayList<Integer> myTopList = JobRecByBoWJaccard.topJobsByBoW(jobID);
%>

In java classes the files are accessed through:

BufferedReader br = new BufferedReader(new FileReader("WebContent/StopWords/stop-words-english1.txt"));

and

private InputStream modelInputT = new FileInputStream("WebContent/OpenNLP_Models/en-token.bin");

The tomcat cannot find the referenced files and someone said use getResourceAsStream, but that is for servlets. I call the java class directly without any servlets.

private InputStream modelInputT = = this.getClass().getClassLoader().getResourceAsStream("WebContent/OpenNLP_Models/en-token.bin");

This cause java class cannot find the file as well. Need help and how to make changes to these java classes?

Was it helpful?

Solution

The tomcat cannot find the referenced files ...

That is because the pathnames are incorrect unless the JVM's current directory is the parent directory of the "WebContent" directory. When you use FileInputStream to open a file, relative pathname are resolved relative to the current directory of the JVM when it was launched.

... and someone said use getResourceAsStream, but that is for servlets.

No. That's not correct either. That method is not "for servlets". The purpose of that method is to open a resource that is on the class / classloader's classpath. If your "WebContent/StopWords/stop-words-english1.txt" is in the webapp's "/WEB-INFO/classes" or in a JAR file in "/WEB-INFO/lib", then getResourceAsStream will find it.


In your case, it seems like you are talking about the "WebContent" directory that corresponds to the default servlet.

In that case, read this Q&A - How can I get real path for file in my WebContent folder?.

So if you are trying to access those files from within a JSP, it seems as if you should be writing this:

  new FileReader("WebContent/StopWords/stop-words-english1.txt")

as this:

  new FileReader(getServletContext().getRealPath(
          "/StopWords/stop-words-english1.txt"))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top