Accessing In-Bundle Resources
Often when developing an OSGi bundle you find yourself needing to access a bundle-local resource, i.e. a resource (file) residing within the bundle itself. The temptation is to do something fairly standard to Java which is:
File file = new File("somedir/somefile.properties");
InputStream is = new FileInputStream(file);
The trouble is that in OSGi you never really know "where you are" and therefore should avoid making assumptions about locality as much as possible. OSGi provides a mechanism through the Bundle itself to locate and open resources. Here is an example of the same action performed within the OSGi framework:
Bundle myBundle = bundleContext.getBundle();
URL myResource = myBundle.getResource("somedir/somefile.properties");
InputStream is = myResource.getInputStream();
As you can see, you need either the Bundle instance itself, or the BundleContext (from which you can get the Bundle instance) in order to access resources within the bundle. The Bundle API provides various method by which you can enumerate, find, and access resources within a bundle. Here they are:
Enumeration findEntries(String path, String filePattern, boolean recurse);
Enumeration getEntryPaths(String path);
URL getEntry(String name);
URL getResource(String name);
Enumeration getResources(String name);
The difference between
getEntry() and
getResource() is that the former loads only from
this bundle, where the later uses the bundle class loader to search for resources within
this bundle
and within bundle dependencies. Consult the JavaDoc for full details of this more advanced behavior.