2014-05-23 17 views
7

我有2个pligins AB。在A的MANIFEST.MF中,我的插件BRequire-Bundle部分。但是,当我尝试从一个得到B的资源像如何从另一个插件获取资源?

ClassFromA.class.getClassLoader().getResource('resource_from_B') 

我得到。如果我把B的资源(文件夹)到A的根一切都像一个魅力。我错过了什么吗?

注:我读的Lars沃格尔article

Bundle bundle = Platform.getBundle("de.vogella.example.readfile"); 
URL fileURL = bundle.getEntry("files/test.txt"); 
File file = null; 
try { 
    file = new File(FileLocator.resolve(fileURL).toURI()); 
} catch (URISyntaxException e1) { 
    e1.printStackTrace(); 
} catch (IOException e1) { 
    e1.printStackTrace(); 
} 

^当我从Eclipse中运行我的插件,但是当我收拾它JAR和尝试从本地更新站点,我得到安装此解决方案的工作

java.lang.IllegalArgumentException: URI is not hierarchical 

PS我也看到了在StackOverflow的几个相关问题,但没能找到答案:

SOLUTION: 非常感谢@格雷格 - 449。所以,正确的代码是:

Bundle bundle = Platform.getBundle("resource_from_some_plugin"); 
URL fileURL = bundle.getEntry("files/test.txt"); 
File file = null; 
try { 
    URL resolvedFileURL = FileLocator.toFileURL(fileURL); 

    // We need to use the 3-arg constructor of URI in order to properly escape file system chars 
    URI resolvedURI = new URI(resolvedFileURL.getProtocol(), resolvedFileURL.getPath(), null); 
    File file = new File(resolvedURI); 
} catch (URISyntaxException e1) { 
    e1.printStackTrace(); 
} catch (IOException e1) { 
    e1.printStackTrace(); 
} 

注:也很非常重要使用URI的3参数的构造函数,以便正确地逃避文件系统的字符。

回答

5

使用

FileLocator.toFileURL(fileURL) 

,而不是当你想使用的URL与FileFileLocator.resolve(fileURL)

当插件打包到jar中时,这会导致Eclipse在临时位置创建一个未打包版本,以便可以使用File访问该对象。

+0

哦,我的!你真棒:-) –

+0

@Lars Vogel我想你在你的文章中有错误 - http://blog.vogella.com/2010/07/06/reading-resources-from-plugin/ –

0

为什么不使用Bundle.getResource?这似乎是OSGi访问资源的方式。

如果您使用ClassFromB.class.getClassLoader而不是A,则您的第一次尝试可能会奏效。

+0

@lulian Dragos ,我在** B **中没有任何课程,只有资源 –