作业帮 > JAVA > 教育资讯

Java培训课程:OSGI如何读取插件中的资源文件

来源:学生作业帮助网 编辑:作业帮 时间:2024/05/09 23:13:55 JAVA
Java培训课程:OSGI如何读取插件中的资源文件
Java培训课程:OSGI如何读取插件中的资源文件JAVA
【网络综合-Java培训课程: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.     }  
JAVA