如何访问OSGi捆绑包中的文件? [英] How do I access a file inside an OSGi bundle?

查看:111
本文介绍了如何访问OSGi捆绑包中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是OSGi的新手,并创建了一个OSGi捆绑包,该捆绑包在Apache Felix OSGi容器中运行. 捆绑软件中包含一个文件资源,我需要将其作为java.io.File传递给方法.要实例化File对象,"file"方案中的URI或字符串形式的路径都是必需的.如何以干净的方式检索其中的任何一个?

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?

我尝试使用 context.getBundle().getResource("/myfile")(上下文的类型为org.osgi.framework.BundleContext)返回URI bundle://6.0:0/myfile. 但是,由于该URI具有捆绑"方案,因此无法使用File(URI uri)构造函数将其转换为File-instance.

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.

一个人可以尝试构造一个到该位置的路径,该路径知道工作目录并利用我的包的bundleId,但是我怀疑这是最佳实践.

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.

有什么想法吗?

推荐答案

由于文件位于文件包内,因此无法使用标准的File来获取文件.您从

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.

因此,如果您可以控制该方法,则我将对其进行更新,使其采用URL甚至是InputStream(因为您可能只想从中读取).为了方便起见,您始终可以提供一个确实采用File的帮助方法.

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.

如果您无法控制该方法,则必须编写一些使用URL的帮助程序方法,并将其流式传输到文件中(例如,

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.

这篇关于如何访问OSGi捆绑包中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆