标签:style blog http color os java ar for art
最近在写Servlet的时候,看到之前的代码里都是这样写的:
InputStream is = xxx.class.getResourceAsStream(filePath);
但是我用另一种写法:
ClassLoader.getSystemResourceAsStream(filePath);
在本地测试的时候也是行得通的,于是把Servlet扔到服务器上,但是到了服务器上,第二种写法就跑不通了。今天找到了下面这个文章:
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.
So if you want to get properties from a static method, it‘s better to use:
SomeClass.class.getClassLoader().getResourceAsStream("XX.properties"));
文章的地址:http://yaodong.yu.blog.163.com/blog/static/121426690200961282221588/
标签:style blog http color os java ar for art
原文地址:http://my.oschina.net/u/1475616/blog/308268