我有2个plguins A 和 B 。在 A 的MANIFEST.MF中,我在 Require-Bundle 部分中有插件 B 。但是,当我尝试从 A 中获取 B 资源时
ClassFromA.class.getClassLoader().getResource('resource_from_B')
我正在 null 。如果我将 B resourсe(文件夹)放到 A的根目录,那么一切都像魅力一样。我错过了什么吗?
注意:我读过Lars Vogel的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
P.S。我还在StackOverflow上阅读了几个相关问题,但未能找到答案:
解: 非常感谢@ greg-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-arg构造函数也是非常重要,以便正确转义文件系统字符。
答案 0 :(得分:6)
使用
FileLocator.toFileURL(fileURL)
当您要将网址与FileLocator.resolve(fileURL)
一起使用时,请而不是File
。
当插件被打包到jar中时,这将导致Eclipse在临时位置创建一个解压缩版本,以便可以使用File
访问该对象。
答案 1 :(得分:0)
为什么不使用Bundle.getResource?这似乎是OSGi访问资源的方式。
如果您使用ClassFromB.class.getClassLoader
代替A
,则首次尝试可能会有效。