Bundle中的资源的访问(如配置Log4j,读取自定义配置文件等)

Bundle运行于OSGi平台,但开发完了后是以Jar文件形式发布的。开发过程中难免会涉及到如何访问Jar文件中的资源的问题。

 

工程目录:

com.myproject.test

    + src

        + Activator.java

    +conf

        + log4j.properties

        +config.txt

 

场景1

需要在Bundle中配置日志,如Log4j。

public class Activator implements BundleActivator {

//实例化一个Logger对象

private static Logger logger = Logger.getLogger(Activator .class);

 /*
  * (non-Javadoc)
  * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
  */
 public void start(BundleContext bundleContext) throws Exception {

    //配置Log4j
    URL url = this.getClass().getResource("/conf/log4j.properties");  //注:路径以"/"开始。
    PropertyConfigurator.configure(url);

 

    //使用Log4j

    logger.info(”message");
 }

 /*
  * (non-Javadoc)
  * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
  */
 public void stop(BundleContext bundleContext) throws Exception {
 }

}

 

场景2

读取自定义配置文件 (配置文件中数据格式为:key=value)

InputStream is = Activator.class.getResourceAsStream(“/conf/config.txt”);  //注:路径以"/"开始。

Map<String, String> m = readConfigFile(is);

 

//读取配置文件config.txt

private static Map<String, String> readConfFile(InputStream is) throws IOException {
  Map<String, String> m = new HashMap<String, String>();
  LineNumberReader reader = new LineNumberReader(new InputStreamReader(is));
  String line = reader.readLine();
  while(line != null) {
   if(line.startsWith("#")) {     //以#开始的为注释,过滤注释行
    line = reader.readLine();
    continue;
   }
   if(line.trim().length() == 0) {    //过滤空白行

    line = reader.readLine();
    continue;
   }
   String[] strs = line.split("\\s*=\\s*");

    m.put(strs[0], strs[1]);
    line = reader.readLine();
  }
  reader.close();
  return m;
 }

 

关于Jar文件中资源的访问,可进一步参考如下:

http://blog.csdn.net/andycpp/article/details/1231619

http://hxraid.iteye.com/blog/483115

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值