0

i want to open a file and return its content. Although it is in the same directory like the class that wants to open the file, the file can't be found. Would be cool if you could help me solving the problem.

Here is the code:

@GET @Produces("text/html") @Path("/{partNO}/") @Consumes("text/html")
public String getPartNoResponseHTML(@PathParam("partNO") String parID) throws WebApplicationException {
PartNoTemplate partNo = getPartNoResponse(parID);

String result = "";

try {
  result = readFile(PART_NO_TEMPLATE_FILE);
} catch (FileNotFoundException e) {
  e.printStackTrace(System.out);
  return e.getMessage() + e.toString();
  // throw new WebApplicationException(Response.Status.NOT_FOUND);
} finally {
  result = result.replace("{partNO}", parID);
  result = result.replace("{inputFormat}", partNo.getFormat().toString());
}

return result;
}

I guess it can't find the file, because its running on tomcat. I'm also using Jersey and JAX-RS. Thank you for your help,

Maxi

Maxiking1011
  • 97
  • 1
  • 2
  • 10

3 Answers3

5

If the file is inside the application WAR (or in a jar) you can try by using

InputStream input = servletContext.getClass().getClassLoader().getResourceAsStream("my_filename.txt");

Your problem is similar (I think) with How can I read file from classes directory in my WAR?

Community
  • 1
  • 1
ioan
  • 489
  • 2
  • 4
4

Try to get the path of the file from ServletContext.

ServletContext context = //Get the servlet context

In JAX-RS to get servlet context use this:

@javax.ws.rs.core.Context 
ServletContext context;

Then get the file from your web application:

File file = new File(context.getRealPath("/someFolder/myFile.txt"));
Paulius Matulionis
  • 23,085
  • 22
  • 103
  • 143
1

You don't post the code that actually tries to read the file, but assuming the file is in the classpath (as you mention it's in the same directory as the class) then you can do:

InputStream in = this.getClass().getResourceAsStream("/SomeTextFile.txt");

See here

Community
  • 1
  • 1
Andres Olarte
  • 4,380
  • 3
  • 24
  • 45