[java] getResourceAsStream() is always returning null
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
WEB-INF/classes, or in
WEB-INF/lib if packaged in a jar file.
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:
But is there a way I can call getServletContext from my Web Service?
If you are using JAX-WS, then you can get a
@Resource private WebServiceContext wsContext;
And then get the
ServletContext from it:
ServletContext sContext= wsContext.getMessageContext() .get(MessageContext.SERVLET_CONTEXT));
This question already has an answer here:
I have the following structure in a Java Web Application:
TheProject -- [Web Pages] -- -- [WEB-INF] -- -- -- abc.txt -- -- index.jsp -- [Source Packages] -- -- [wservices] -- -- -- WS.java
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
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 :/
I think this way you can get the file from "anywhere" (including server locations) and you do not need to care about where to put it.
It's usually a bad practice having to care about such things.
I had the same problem when I changed from Websphere 8.5 to WebSphere Liberty.
FileInputStream instead of
getResourceAsStream(), because for some reason WebSphere Liberty can't locate the file in the
The script was :
FileInputStream fis = new FileInputStream(getServletContext().getRealPath("/") + "\WEBINF\properties\myProperties.properties")
Note: I used this script only for development.