加载指定文件的方式,使用getResourceAsStream("fileName")

来源:互联网 发布:网络问诊国家政策 编辑:程序博客网 时间:2024/06/10 16:36

在Java Web等工程中,我们可以使用下面的方式来加载一个文件流

InputStream in=DBUtil.class.getResourceAsStream("database.properties")

此时,database.properties 和 DBUtil 在同一级目录下面。

getResourceAsStream方法解释:
Finds a resource with a given name. The rules for searching resources associated with a given class are implemented by the defining class loader of the class. This method delegates to this object’s class loader. If this object was loaded by the bootstrap class loader, the method delegates to ClassLoader.getSystemResourceAsStream.

Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:

• If the name begins with a ‘/’ (‘\u002f’), then the absolute name of the resource is the portion of the name following the ‘/’.
• Otherwise, the absolute name is of the following form:
modified_package_name/name
Where the modified_package_name is the package name of this object with ‘/’ substituted for ‘.’ (‘\u002e’).

中文解释:
通过一个名称找到资源。搜索规则跟给定的类有关系,它是通过定义这个类的类加载器来实现的。
这个方法会委派给这个对象的类加载器,如果这个对象是由启动类加载器加载的,那么方法就会为派给ClassLoader.getSystemResourceAsStream
在委派之前,一个资源路径是由给定的资源名称通过下面的算法来构造的:
如果资源的名称由/开头,那么资源的绝对名称就是/后面的那一部分,
否则的话,绝对名称就是:modified_package_name/name
modified_package_name是这个对象的包名用’/’替代’.’,因为包的形式是com.abc.ClassA.class这样的形式,实际上是com/abc/ClassA.class

总结:
也就是说,只要资源和类在同一级目录下面,无论资源名称的前面加不加/或./都可以找到。

0 0
原创粉丝点击