How to reference an included file in OSGi bundle when performing java.io.File or FileInputStream

半腔热情 提交于 2019-11-30 12:15:55

The Bundle interface has a getEntry(java.lang.String path) method which return an Url and is documented as:

Returns a URL to the entry at the specified path in this bundle. This bundle's class loader is not used to search for the entry. Only the contents of this bundle are searched for the entry. The specified path is always relative to the root of this bundle and may begin with "/". A path value of "/" indicates the root of this bundle.

I think the answer should be as simple as the following:

URL cssFile = this.getClass().getResource("/resources/example.css");

I.e. make sure there is a leading slash in the path. You had it without a leading slash, which would make it "relative" to the class you're calling from.

Alternatively the following should work:

this.getClass().getClassLoader().getResource("resources/example.css");

If you are building with Eclipse/Equinox, then you can get the location of a Bundle from outwith the BundleContext contained within the BundleActivator by calling something like:

Bundle yourBundle = Platform.getBundle("bundleSymbolicName");
Path relativePathToBundle = new Path("/relativePath");
FileLocator.openStream(yourBundle, relativePathToBundle, false); 

The Platform and FileLocator classes come from the org.eclipse.core.runtime plug-in so if you have a dependency on that then the above should allow you to get access to your resource.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!