getResourceAsStream() is always returning null

Andreas Grech picture Andreas Grech · May 9, 2010 · Viewed 117.7k times · Source

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 :/

Answer

Jaroslav Záruba picture Jaroslav Záruba · May 9, 2010

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.