This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Why ClassLoader.getSystemResourceAsStream("/resources/validfilename.cfg") returns null and getClass().getClassLoader().getSystemResourceAsStream() returns valid IP stream ? any help, is apprecaited. Thanks
ClassLoader.getSystemResourceAsStream uses the system ClassLoader (ClassLoader.getSystemClassLoader) to search for the resource. this.getClass().getClassLoader().getResourceAsStream() uses the same ClassLoader that loaded the class for "this" Object. That ClassLoader might be a child of the system ClassLoader, and thus could have access to resources the system ClassLoader does not have. But since it is a child of the System ClassLoader, it also will ask its parent (System) to help it find resources. So using this method will allow you to find things in that ClassLoader AND in the System ClassLoader. The search order is defined in the javadoc for ClassLoader.getResource (parent(s) first, then child). For example, say you were running some code from a Servlet. The System ClassLoader contains whatever you put in CLASSPATH when you started the Web Server, but the servlet class is probably loaded by another ClassLoader that the server created to handle the WebApp's WEB-INF/lib and WEB-INF/classes directories. Things in those directories would be accessible using that WebApp's ClassLoader, but would not be in CLASSPATH - so the System ClassLoader does not know about them. I'm not sure I explained that well - hope it helps.
Joined: Oct 21, 2002
Thanks for your input. ..so how can i force my system ClassLoader to find this file.do i hav make it relative to classpath ? As system class loader have static methods to load resources, i would prefer to use system class loader, where as getClass().getClassLoader().getSystemResourceAsStream("") would force me create an object instance each time i try to get the resource . again, thanks for your IP and also Java Ranch- you guys really doing a great job
Joined: Jul 24, 2002
Usually, you should not use the system classloader because it would prevent things from working "naturally" in examples of servlets, ejbs, applets, etc. Usually, you want the code to get the resource "from the same place my class came from". It's much more portable and does not rely on the user setting CLASSPATH or anything. If you just want to know how to do this in a static method, try this:
Otherwise, if you must use system classloader, then put the location in CLASSPATH. For example, if the resource is "/resources/validfilename.cfg" and that file actually lives at "/usr/local/mystuff/resources/validfilename.cfg", then put "/usr/local/mystuff" in CLASSPATH.