如果写一个类需要动态的获取某个文件的位置,从而能够获取此文件的资源。那么,使用Class.getResourceAsStream()方法便可以。
这样就不用每次去修改代码中文件的绝对地址或详细地址了。
这是它的源码:
我们可以看到它最终返回了一个输入流,也就是返回一个InputStream对象方便对此文件资源通过IO流进行获取。
@CallerSensitive
public InputStream getResourceAsStream(String name) {
name = resolveName(name);
Module thisModule = getModule();
if (thisModule.isNamed()) {
// check if resource can be located by caller
if (Resources.canEncapsulate(name)
&& !isOpenToCaller(name, Reflection.getCallerClass())) {
return null;
}
// resource not encapsulated or in package open to caller
String mn = thisModule.getName();
ClassLoader cl = getClassLoader0();
try {
// special-case built-in class loaders to avoid the
// need for a URL connection
if (cl == null) {
return BootLoader.findResourceAsStream(mn, name);
} else if (cl instanceof BuiltinClassLoader) {
return ((BuiltinClassLoader) cl).findResourceAsStream(mn, name);
} else {
URL url = cl.findResource(mn, name);
return (url != null) ? url.openStream() : null;
}
} catch (IOException | SecurityException e) {
return null;
}
}
下面是我找的一个比较好的对getResourceAsStream用法的解释,共勉!