getResourceAsStream 工作后返回 null [英] getResourceAsStream returning null after it had worked
问题描述
我正在从 servlet 容器运行应用程序.此应用程序生成的信件源自与 jar 一起打包的一些文件模板.我通过 Class.getResourceAsStrem
获取了这些文件,并且该应用程序运行良好.
I am running an application from a servlet container. This application produces letters which are derived from some file templates that packed with the jar. I get hold of these files by Class.getResourceAsStrem
and the application works perfectly fine.
然而,经过数千次调用,该方法突然返回null
,并继续返回null
,直到应用程序重新启动.我对此没有任何解释,我看不出为什么会突然发生这种情况.
However, after thousands of invocations, the method suddently returns null
and continues to return null
until the application is restarted. I have no explanation for this and I cannot see a reason why this would suddenly happen.
我首先认为这可能是因为未关闭的流指向相同的资源,但我在打开它后立即将流处理包装在 catch
-try
-block 中.此外,堆转储不会显示此类流对象,而且我认为这应该导致 IOException
代替.另外,它在javadoc中说
I first thought this might be because of unclosed streams pointing to the same resource but I am wrapping the stream processing in a catch
-try
-block right after opening it. Also, a heap dump does not show such stream objects and I furthermore think that this should result in an IOException
instead. Also, it says in the javadoc
一个 InputStream 对象,如果没有找到同名的资源,则为 null
A InputStream object or null if no resource with this name is found
但是为什么应用程序突然无法再找到之前成功找到的资源.
But why would the application suddenly not longer be able to find a resource it successfully found before.
有什么想法吗?
推荐答案
我想我找到了原因.ClassLoader.getResourceAsStream(String)
最终委托给 Class.getResourceAsStream
的实现如下:
I think I found the reason. ClassLoader.getResourceAsStream(String)
to which Class.getResourceAsStream
eventually delegates is implemented like this:
public InputStream getResourceAsStream(String name) {
URL url = getResource(name);
try {
return url != null ? url.openStream() : null;
} catch (IOException e) {
return null;
}
}
我猜发生了 IOException
并且确实存在泄漏的打开文件.然而,这个异常被吞没了,我得到了一个 null
指针作为回报.天才 API...
I guess there is an IOException
occurring and that there are indeed leaking open files. However, this exception gets swallowed and I get a null
pointer in return. Genius API...
更新:在查看堆转储后,我发现应用程序代码正在泄漏文件.该死的,ClassLoader
实现,用 NullPointerException
s 误导了我.
Update: After looking at a heap dump, I found application code that was leaking files. Damn you, ClassLoader
implementation, misdirecting me with NullPointerException
s.
这篇关于getResourceAsStream 工作后返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!