如何访问OSGi包中的文件?

mts*_*tsz 14 osgi file-access apache-felix

我是OSGi的新手,并创建了一个OSGi-bundle,我在Apache Felix OSGi-container中运行.捆绑包中包含一个文件资源,我需要将其作为传递给方法java.io.File.要实例化File-object,需要"file"-scheme中的URI或字符串作为字符串.如何以干净的方式检索任何这些?

我尝试使用 context.getBundle().getResource("/myfile")(org.osgi.framework.BundleContext返回类型的上下文)返回URI bundle://6.0:0/myfile.但是这个URI不能使用File(URI uri)构造函数转换为File-instance,因为它具有"bundle"-scheme.

可以尝试构建一个知道工作目录的位置路径并利用我的bundle的bundleId,但我怀疑这是最好的做法.

有任何想法吗?

Ang*_*jpt 13

由于文件在您的包中,因此您无法使用标准访问它File.在URL你得到Bundle.getResource()是获得这些资源的正确方法,因为在OSGi的API旨在还对系统工作,没有实际的文件系统.我总是试图坚持使用OSGi API而不是使用特定于框架的解决方案.

所以,如果你可以控制这个方法,我会把它更新为一个URL,甚至一个InputStream(因为你可能只是想从中读取).为方便起见,您总是可以提供一个帮助方法,它确实需要一个File.

如果您无法控制该方法,则必须编写一些辅助方法,将其URL流式传输到文件中(例如,File.createTempFile()可能会执行此操作).


小智 7

也许API是可混淆的,但您可以访问OSGI包中的文件,如下所示:

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();
Run Code Online (Sandbox Code Playgroud)

getResource将像OSGI类加载器理论一样通过整个OSGI容器找到资源.
getEntry将从本地捆绑包中找到资源.并且返回的url可以转换为file而不是inputStream.
这是一个与此相同的问题:无法访问Bundle Resource/File(OSGi) 希望这对您有所帮助.