unusual behavior of ClassLoader
public InputStream getResourceAsStream ( Class className, String name){
InputStream in = null;
in = className.getClassLoader().getResourceAsStream(name);
return in;
}
className : loaded class using Class.forName().
name : name of the resource present in 开发者_运维百科the same directory.
Problem : result is always null.
Could anyone tell me what is wrong with the above code though I have tried many ways.
had been facing the same problem a few days ago myself. But i found that the way i passed the name was wrong. i mean i had messed up with the relative path and absolute path. if its unable to find the name then it will throw a nullpointerException.
To check if your code is fine and the problem is only with the name, Just hard code the entire path for the name and make sure it loads. If that is so, then its just apath issue that u have to rectify. Secondly, the only other problem is if you are loading it from static block then the syntax might differ a bit. Else there should be no problem.
A good place where in u can check out the loading of file is http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html?page=2
let me know if this helps..
if all your images are within the jar file, then i am assuming that you would have made a seperate images folder. that way, u can access all the images in the same manner by simply replacing the image name. what i believe is, once u have made the jar file, everything is exploded in it. if ur images is placed under the parent folder, i.e com/demo/images then u can simply use the above method and provide the aboslute path i.e getResourceasStream(/com/demo/images/image001.jpeg) . There is a beter way to do it as well. When u deploy on the server u can create a separate images folder as a system property, and then simply do a system.getenv(prop_name) so it can starightaway traverse to that image location. There are several ways to do it actually.
精彩评论