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()
也是可以取到的

猜你喜欢

转载自marsvaadin.iteye.com/blog/1263397