Thread.currentThread().getContextClassLoader().getResourceAsStream() returns null
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.
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.
A resource is something on the classpath. Paths for resources always use /
as file separator and not 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/
.
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.
Ratha
Updated on June 04, 2022Comments
-
Ratha almost 2 years
I have following code block in my application;
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(FilePath);
Here 'FilePath' is an absolute path of the file.
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'.
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..
Any clue on this?