How do I access a file inside an OSGi bundle?

前端 未结 3 1810
梦谈多话
梦谈多话 2021-02-19 01:19

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

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-19 01:50

    Maybe the API is confusable, but You can access a file inside an OSGI bundle like this:

    URL url = context.getBundle().getResource("com/my/weager/impl/test.txt");
    
    // The url maybe like this: bundle://2.0:2/com/my/weager/impl/test.txt
    // But this url is not a real file path :(, you could't use it as a file.
    // This url should be handled by the specific URLHandlersBundleStreamHandler, 
    // you can look up details in BundleRevisionImpl.createURL(int port, String path)
    System.out.println(url.toString());
    
    BufferedReader br =new BufferedReader(new InputStreamReader(url.openConnection().getInputStream()));
    while(br.ready()){
        System.out.println(br.readLine());
    }
    br.close();
    

    getResource will find the resource through the whole OSGI container just like OSGI classloader theory.
    getEntry will find the resource from local bundle. and the return url could be convert to file but inputStream.
    Here is a question same with this: No access to Bundle Resource/File (OSGi) Hope this helping you.

提交回复
热议问题