ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

如何在执行java.io.File或FileInputStream时引用OSGi包中的包含文件

2019-10-05 18:01:43  阅读:213  来源: 互联网

标签:java osgi bundle classpath


我正在使用aQute Bnd工具集来创建一个OSGi包,并打包了一些相关的“资源”文件.这包括我创建的资源目录中的* .css文件和* .xsd文件.

我在bundle.bnd文件中包含以下内容:

Include-Resource: resources/=resources/ 

当我进行构建时,生成的* .jar文件在jar包文件的顶级目录的resources目录中包含* .css和* .xsd文件.

但是,在实际代码中,我很难尝试将其作为类路径的一部分引用:

我尝试过以下方法:

new File("resources/example.css");

我也尝试过:

URL cssFile = this.getClass().getResource("resources/example.css");
try
{
   file = new File(cssFile.toURI()));
}
catch(Exception e)
{
   e.printStackTrace();  
}

我得到一个NullPointException错误或无法找到文件IOException错误(取决于我使用哪一个).我在调试配置模式下运行Eclipse Equinox以及Apache Felix(我们用于部署)时遇到此错误.注意我试图在BundleActivator之外的Java类中执行此操作.

我是否需要始终参考BundleActivator的上下文,例如?

 /*
 * (non-Javadoc)
 * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
 */
 @Override
 public void start(BundleContext context) throws Exception 
 {   
     /* Service to host the Bundle interface. */
     ServletContainerService service = new ServletContainerService();
     service.addServlet(new ServletContainer(new AxisServlet(), true));
     this.serverReg = context.registerService(ServletContainerService.class.getName(), service, null);

     cssFile = new File(context.getClass.getResource("resource/example.css")); 
 }

我认为上面的内容会起作用,但意味着我将不得不传递cssFile参考,而这个参考似乎并不优雅.

有没有办法在bundle / .jar文件的任何给定Java类中引用bundle jar文件中包含的’resources’目录的路径?如果它涉及BundleContext,有没有办法在任何Java类中引用它?

任何帮助都感激不尽.

我看过Including additional resources with OSGi bundles但看起来你需要BundleContext.

我可能找到了一个可能的解决方案:http://www.vogella.de/blog/tag/plugin/

看起来Vogella有一些示例代码:

URL url;
try {
        url = new URL("platform:/plugin/de.vogella.rcp.plugin.filereader/files/test.txt");
    InputStream inputStream = url.openConnection().getInputStream();
    BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
    String inputLine;

    while ((inputLine = in.readLine()) != null) {
        System.out.println(inputLine);
    }

    in.close();

} catch (IOException e) {
    e.printStackTrace();
}

有没有人知道如果它不是一个插件,如果我使用不同的OSGi环境,这条路径是否相同,例如. Equinox Eclipse与Apache Felix?
例如url = new URL(“platform:/plugin/de.vogella.rcp.plugin.filereader/files/test.txt”);

解决方法:

Bundle interface有一个返回Url的getEntry(java.lang.String path)方法,记录为:

返回此捆绑包中指定路径的条目的URL.此捆绑包的类加载器不用于搜索条目.仅搜索此包的内容以查找该条目.
指定的路径始终相对于此捆绑包的根,可以以“/”开头.路径值“/”表示此捆绑包的根.

标签:java,osgi,bundle,classpath
来源: https://codeday.me/bug/20191005/1857029.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有