Resources.getResourceAsStream用法

Resources(com.ibatis.common.resource.*)

Resources 类为从类路径中加载资源,提供了易于使用的方法。处理 ClassLoader 是一项
富于挑战的工作,尤其是应用服务器/容器的情况下。

Resources 类试图简化这些工作,Resources 类常用于以下几种情况:

    1.从类路径加载 SQL Map 配置文件(如 sqlMap-config.xml)。 
    2. 从类路径加载 DAO Manager 配置文件(如 dao.xml)。 
    3. 从类路径加载各种.properties 文件。 

加载一个资源有很多方式,包括:
1.对于简单的只读文本数据,加载为 Reader。
Reader getResourceAsReader(String resource);
2. 对于简单的只读二进制或文本数据,加载为 Stream。

Stream getResourceAsStream(String resource); 

3.对于可读写的二进制或文本文件,加载为 File。

File getResourceAsFile(String resource); 

/4. 对于只读的配置属性文件,加载为 Properties。

Properties getResourceAsProperties(String resource); 

/5. 对于只读的通用资源,加载为 URL。
按以上的顺序,Resources 类加载资源的方法如下:

Url getResourceAsUrl(String resource); 

在以上每个方法中,加载资源和加载 Resources 类的为同一个 ClassLoader,或者,如果 失败,将使用系统的
ClassLoader。 在某些环境下(比如某些应用服务器), ClassLoader 可能是个麻烦事,您可以指定所使用的
ClassLoader(比如使用加载应用的 ClassLoader)。

上面每个方法都有相应把 ClassLoader 作为参数的方法。它们是:

Reader getResourceAsReader (ClassLoader classLoader, String resource); 
Stream getResourceAsStream (ClassLoader classLoader, String resource); 
File getResourceAsFile (ClassLoader classLoader, String resource); 
Properties getResourceAsProperties (ClassLoader classLoader, String resource); 
Url getResourceAsUrl (ClassLoader classLoader, String resource); 

以上方法的 resource 参数名称应该是全限定名,加上全文件/资源名。
例如,如果在类路径中有资源“com.domain.mypackage.MyPropertiesFile.properties”,您使用下面的代码加载

String resource = “com/domain/mypackage/MyPropertiesFile.properties”;

Properties props = Resources.getResourceAsProperties (resource);

同样地,您可以从类路径加载 SQL Map 配置文件为一个 Reader。假设它在类路径的
properties 目录下(properties.sqlMap-config.xml)。

String resource = “properties/sqlMap-config.xml”; Reader reader =
Resources.getResourceAsReader(resource); SqlMapClient sqlMap =
XmlSqlMapBuilder.buildSqlMap(reader);

  • 15
    点赞
  • 66
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值