I am new to OSGi and created an OSGi-bundle which I run in the Apache Felix OSGi-container.
There is a file resource contained in the bundle, which I need to pass to a method as a java.io.File
. To instantiate a File-object, either an URI in the "file"-scheme or the path as string is necessary. How do I retrieve any of those in a clean way?
I tried using the
context.getBundle().getResource("/myfile")
(where context is of type org.osgi.framework.BundleContext
) which returns the URI bundle://6.0:0/myfile
.
But this URI can't be converted to a File-instance using the File(URI uri)
constructor since it has the "bundle"-scheme.
One could try to construct a path to the location knowing the working directory and exploiting the bundleId of my bundle, but I doubt this is the best practice.
Any ideas?
Since the file is inside your bundle, there is no way for you to get to it using a standard File
. The URL
you get from Bundle.getResource()
is the correct way to get to these resources, since the OSGi APIs are intended to also work on systems without an actual file system. I would always try to stick to the OSGi API instead of using framework-specific solutions.
So, if you have control over the method, I would update it to take a URL
, or maybe even an InputStream
(since you probably just want to read from it). For convenience, you can always provide a helper method that does take a File
.
If you don't have control over the method, you will have to write some helper method that takes the URL
, streams it out to a file (for instance, File.createTempFile()
will probably do the trick.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With