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

在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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值