No access to Bundle Resource/File (OSGi)

后端 未结 2 1740
独厮守ぢ
独厮守ぢ 2020-12-05 12:22

at the moment i\'m developing an OSGi based WebApp with Jetty and Equinox (see: http://wiki.eclipse.org/Jetty/Tutorial/EclipseRT-Jetty-Starter-Kit). Everything ist fine so f

相关标签:
2条回答
  • 2020-12-05 12:29

    Solved!!! Thanks to Danail Nachev (see comment) who brought me to the right way! After some searching after "bundleentry://xyz" and "bundleresource://" i found this mailinglist post: http://www.mail-archive.com/felix-dev@incubator.apache.org/msg02410.html

    So the answer is the following (Usging (Equinox) FileLocator):

    URL configURL = context.getBundleContext().getBundle().getResource("config.csv");
    File configFile = new File(FileLocator.toFileURL(configURL).getPath());
    

    But (also asked in that mailinglist) it would be interesting if there exists other solutionss wich are not only applicable for Equinox?

    0 讨论(0)
  • 2020-12-05 12:39

    You are correctly retrieving the resource from the bundle. I'll suggest to get familiar with the difference between getEntry(), getResource() and getDataFile().

    Because methods returns you correct URLs, this means that the resource are correctly located and the problem is in how you read them.

    The two ways to use them are:

    1. Open InputStream from the URL directly:
    
        URL configURL = context.getBundleContext().getBundle().getEntry("configuration/data/config.csv");
        if (configURL != null) {
            InputStream input = configUrl.openStream();
            try {
                // process your input here or in separate method
            } finally {
                input.close();
            }
        }
       
    1. Convert the URL to File. This approach is not recommended, because it makes the assumption that the Bundle is deployed as directory (and not in archive). It is however helpful if you must deal with legacy libraries which requires you to use File objects. To convert to File you cannot use URL.getPath() method, because Equinox has its own format for the URLs. You should use org.eclipse.core.runtime.FileLocator class to resolve to a File. The FileLocator.getBundleFile(Bundle) does exactly what you want.
    0 讨论(0)
提交回复
热议问题