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

来源:互联网 发布:url域名 网站 ip的区别 编辑:程序博客网 时间:2024/04/30 12:20

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

原创粉丝点击