OSGI如何读取插件中的资源文件

思路就是通过bundleContext来取得资源。
首先,要在对应的插件中先建立一个Activator需要实现BundleActivator接口,
代码

Java代码   收藏代码
  1. import  org.osgi.framework.BundleActivator;  
  2. import  org.osgi.framework.BundleContext;  
  3.   
  4. public   class  Activator  implements  BundleActivator {  
  5.   
  6.   private   static  BundleContext bundleContext;  
  7.   
  8.   public   static  BundleContext getBundleContext() {  
  9.     return  bundleContext;  
  10.   }  
  11.   
  12.   public   void  start(BundleContext context)  throws  Exception {  
  13.      Activator.bundleContext = context;     
  14.   }  
  15.   
  16.     public   void  stop(BundleContext context)  throws  Exception {  
  17.           
  18.     }  
  19. }  



然后再需要查找资源的地方,取得bundleContext,通过bundleContext的getResource方法取得URL类型的resource,代码:

Java代码   收藏代码
  1. public   static  InputStream getResourceByContext(String path) {  
  2.         try  {  
  3.             BundleContext bundleContext = Activator.getBundleContext();  
  4.             URL resource = bundleContext.getBundle().getResource("/web"  + path);  
  5.             InputStream in = resource.openStream();  
  6.             if  (in ==  null ) {  
  7.                 String msg = "\nNot found \""  + path +  "\";" ;  
  8.                 log.error(msg);  
  9.             }  
  10.             return  in;  
  11.         } catch  (IOException e) {  
  12.             e.printStackTrace();  
  13.         } finally  {  
  14.         }  
  15.         return   null ;  
  16.     }  



注意这里的路径,是从直接写工程文件夹下开始写。


另外,楼下说的
Thread.currentThread().getContextClassLoader().getResource()
也是可以取到的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值