Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getResourceAsStream() is always returning null [duplicate]

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

like image 359
Andreas Grech Avatar asked May 09 '10 09:05

Andreas Grech


People also ask

Should we close getResourceAsStream?

You should always close streams (and any other Closeable, actually), no matter how they were given to you. Note that since Java 7, the preferred method to handle closing any resource is definitely the try-with-resources construct.

What is getResourceAsStream Java?

The getResourceAsStream method returns an InputStream for the specified resource or null if it does not find the resource. The getResource method finds a resource with the specified name. It returns a URL to the resource or null if it does not find the resource. Calling java.

How do you send paths in getResourceAsStream?

getResourceAsStream , send the absolute path from package root, but omitting the first / . If you use Class. getResourceAsStream , send either a path relative the the current Class object (and the method will take the package into account), or send the absolute path from package root, starting with a / .


1 Answers

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.

like image 175
Jaroslav Záruba Avatar answered Sep 30 '22 11:09

Jaroslav Záruba