问题描述
我在 Java Web 应用程序中有以下结构:
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
中,我在 Web 方法中使用以下代码:
In WS.java
, I am using the following code in a Web Method:
InputStream fstream = this.getClass().getResourceAsStream("abc.txt");
但它总是返回一个空值.我需要从那个文件中读取,我读到如果你把文件放在 WEB-INF
中,你可以用 getResourceAsStream
访问它们,但该方法总是返回一个null
.
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?
顺便说一句,奇怪的是这是有效的,但是在我对项目执行Clean and Build
后,它突然停止工作:/
Btw, the strange thing is that this was working, but after I performed a Clean and Build
on the Project, it suddenly stopped working :/
推荐答案
据我所知,该文件必须在 'this'
类所在的文件夹中,即不在 中WEB-INF/classes
但嵌套更深(除非你在默认包中编写):
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
将文件放入您的 java 源代码应该可以工作,编译器将该文件与类文件一起复制.
Putting the file in to your java sources should work, compiler copies that file together with class files.
这篇关于getResourceAsStream() 总是返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!