views:

268

answers:

2

I have the following structure in a Java Web Application:

TheProject
  -- [Web Pages]
  -- -- [WEB-INF]
  -- -- -- abc.txt
  -- -- index.jsp
  -- [Source Packages]
  -- -- [wservices]
  -- -- -- WS.java

In WS.java, I am using the following code in a Web Method:

InputStream fstream = this.getClass().getResourceAsStream("abc.txt");

But it is always returning a null. I need to read from that file, and I read that if you put the files in WEB-INF, you can access them with getResourceAsStream, yet the method is always returning a null.

Any ideas of what I may be doing wrong?

Btw, the strange thing is that this was working, but after I performed a Clean and Build on the Project, it suddenly stopped working :/

+2  A: 

To my knowledge the file has to be right in the folder where the 'this' class resides. I.e. not in WEB-INF/classes but nested even deeper (unless you write in a default package)...

net/domain/pkg1/MyClass.Java
net/domain/pkg1/abc.txt

Putting the file in to your java sources should work, compiler copies that file together with class-files.

Jaroslav Záruba
+1 Cheers mate, it worked. I moved the file to `wservices` and its working now
Andreas Grech
+1  A: 

A call to Class#getResourceAsStream(String) delegates to the class loader and the resource is searched in the class path. In other words, you current code won't work and you should put abc.txt in WEB-INF/classes, or in WEB-INF/lib if packaged in a jar file.

Or use ServletContext.getResourceAsStream(String) which allows servlet containers to make a resource available to a servlet from any location, without using a class loader. So use this from a Servlet:

this.getServletContext().getResourceAsStream("/WEB-INF/abc.txt") ;

But is there a way I can call getServletContext from my Web Service?

If you are using JAX-WS, then you can get a WebServiceContext injected:

@Resource
private WebServiceContext wsContext;

And then get the ServletContext from it:

ServletContext sContext= wsContext.getMessageContext()
                             .get(MessageContext.SERVLET_CONTEXT));
Pascal Thivent
But is there a way I can call `getServletContext` from my Web Service?
Andreas Grech