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 :/
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.
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.
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 / .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With