Java Thread.currentThread().getContextClassLoader().getResourceAsStream() 返回 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21020350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Thread.currentThread().getContextClassLoader().getResourceAsStream() returns null
提问by Ratha
I have following code block in my application;
我的应用程序中有以下代码块;
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(FilePath);
Here 'FilePath' is an absolute path of the file.
这里的“FilePath”是文件的绝对路径。
Above code works fine in linux and in windows when i run the application in normal mode.(ie: in command prompt) But this is NOT working, when I run the application as a windows service. I get input stream as 'null'.
当我在正常模式下运行应用程序时,上面的代码在 linux 和 windows 中工作正常。(即:在命令提示符下)但是当我将应用程序作为 windows 服务运行时,这不起作用。我得到输入流为“空”。
Anyone encountered such issue before? I could not find any information regarding this other than java classloaders . Here we use "ContextClassLoader", which is the right classloader to be used..
以前有人遇到过这样的问题吗?除了 java classloaders 之外,我找不到任何关于此的信息。这里我们使用“ContextClassLoader”,这是要使用的正确类加载器。
Any clue on this?
这有什么线索吗?
采纳答案by Aaron Digulla
I think this happens because you have "." (the current folder) on the classpath. That is a) a bad idea and b) makes your app break in odd ways.
我认为这是因为您有“。” (当前文件夹)在类路径上。那是 a) 一个坏主意 b) 使您的应用程序以奇怪的方式中断。
What you need to understand is the difference between a file and a resource. A file is something outside of the classpath.
您需要了解的是文件和资源之间的区别。文件是类路径之外的东西。
You should use File
and FileReader
to access them.
您应该使用File
和FileReader
访问它们。
A resource is something on the classpath. Paths for resources always use /
as file separator and not File.separator
.
资源是类路径上的东西。资源的路径总是/
用作文件分隔符而不是File.separator
.
Another way to fix this is to add $HOME/repository/
(Linux) or %HOME%/repository/
to the classpath and load the resource using "resources/api_templates/api.xml"
. for this to work, resources
must be a folder in $HOME/repository/
.
解决此问题的另一种方法是添加$HOME/repository/
(Linux) 或%HOME%/repository/
类路径并使用"resources/api_templates/api.xml"
. 为此,resources
必须是$HOME/repository/
.
If you don't do this, then all files in your home directory (or whatever directory you happen to start the application in) are added as resources to the classpath.
如果您不这样做,则您的主目录(或您碰巧在其中启动应用程序的任何目录)中的所有文件都将作为资源添加到类路径中。