getResourceAsStream() is always returning null [duplicate]
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.
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));