ClassLoader.getSystemResource();
ClassLoader.getSystemResourceAsStream();
//这些方法用来获得在同一CLASSPATH中的资源
[size=large][b]System Resources[/b][/size]
A system resource is a resource that is either built-in to the system, or kept by the host implementation in, for example, a local file system. Programs access system resources through the ClassLoader methods getSystemResource and getSystemResourceAsStream.
For example, in a particular implementation, locating a system resource may involve searching the entries in the CLASSPATH. The ClassLoader methods search each directory, ZIP file, or JAR file entry in the CLASSPATH for the resource file, and, if found, returns either an InputStream, or the resource name. If not found, the methods return null. A resource may be found in a different entry in the CLASSPATH than the location where the class file was loaded.
[color=red]System resources are those that are handled by the host implemenation directly. For example, they may be located in the CLASSPATH.(当要定位的资源是本地直接实现的,例如:是位于在CLASSPATH中的)[/color]
[color=red]The methods in ClassLoader use the given String as the name of the resource without applying any absolute/relative transformation (see the methods in Class). The name should not have a leading "/".(这些在ClassLoader内的方法不会进行绝对、相对地址转换,所以所传的参数name不应该以“/”开头)[/color]
ClassLoader.getResource()
ClassLoader.getResourceAsStream()
//这些方法可以根据不同的ClassLoader有不同获得方法。
//例如:AppletClassLoader,可以通过网络获得资源。
[size=large][b]Non-System Resources[/b][/size]
The implementation of getResource on a class loader depends on the details of the ClassLoader class. For example, AppletClassLoader:
[list]
[*]First tries to locate the resource as a system resource; then, if not found,
[*]Searches through the resources in archives (JAR files) already loaded in this CODEBASE; then, if not found,
[*]Uses CODEBASE and attempts to locate the resource (which may involve contacting a remote site).
[/list]
[color=red]All class loaders will search for a resource first as a system resource, in a manner analogous to searcing for class files.[/color] This search rule permits overwriting locally any resource. Clients should choose a resource name that will be unique (using the company or package name as a prefix, for instance).
Class.getResource()
Class.getResourceAsStream()
//在不确定类的加载方式时使用。
//会根据加载类的ClassLoader去决定怎样的方式去加载资源。
//就像ClassLoader加载Class一样。例如是AppletClassLoader网络加载,提供很好的灵活性。
会先把参数作绝对地址和相对地址转换。再委派给ClassLoader相对应的方法。
“/”开头的地址就是绝对地址,否则就是相对class的地址(会在地址前加上class的路径)。实现转换的方法如下:
private String resolveName(String name) {
if (name == null) {
return name;
}
if (!name.startsWith("/")) {
Class c = this;
while (c.isArray()) {
c = c.getComponentType();
}
String baseName = c.getName();
int index = baseName.lastIndexOf('.');
if (index != -1) {
name = baseName.substring(0, index).replace('.', '/') + "/" + name;
}
} else {
name = name.substring(1);
}
return name;
}
参考:[url]http://docs.oracle.com/javase/1.5.0/docs/guide/lang/resources.html[/url]