r2 - 07 Jun 2007 - 22:24:09 - BrettWooldridgeYou are here: TWiki >  Developer Web  > InBundleResources

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.
Edit | WYSIWYG | Attach | Printable | Raw View | Backlinks: Web, All Webs | History: r2 < r1 | More topic actions
Developer.InBundleResources moved from Main.InBundleResources on 07 Jun 2007 - 22:24 by BrettWooldridge - put it back
 
Powered by TWiki
This site is powered by the TWiki collaboration platformCopyright © by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback