目前,我正在使用 Jetty 和 Equinox 开发基于 OSGi 的 WebApp(参见:http://wiki.eclipse.org/Jetty/Tutorial/EclipseRT-Jetty-Starter-Kit)。
到目前为止一切都很好,但我 无法访问我自己的包的某些文件/资源 .
位置/路径是“configuration/data/config.csv”和“configuration/data/data.zip”。
我已经测试了一切:
context.getBundleContext().getBundle().getEntry("config.csv");
context.getBundleContext().getBundle().getResource("config.csv");
this.getClass().getClassLoader().getResource("config.csv");
context.getBundleContext().getDataFile("config.csv");
当然还有所有可能的路径变体,例如:“configuration/data/config.csv”、“/configuration/data/config.csv”、“\configuration/data/config.csv”、“/config.csv”。
此外,我已将文件夹添加到 OSGi 类路径(在 MANIFEST.MF 中):
Bundle-ClassPath: .,
configuration/data/
结果 URL 看起来总是像这样(或 null):“configuration/CBR-Data/config.csv”,当我将它传输到文件对象“D:\configuration\CBR-Data\config.csv”时。
但我真正不明白的是,我的 DS 之一的属性文件已完美加载:
<properties entry="configuration/dsconfig.properties"/>
有人有想法/提示或其他什么吗?我快疯了...
最佳答案
您正在正确地从包中检索资源。我建议您熟悉 getEntry()、getResource() 和 getDataFile() 之间的区别。
因为方法返回正确的 URL,这意味着资源被正确定位,问题在于你如何阅读它们。
使用它们的两种方法是:
InputStream
来自 URL
直接:
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();
}
}
URL
至 File
.不推荐这种方法,因为它假设 Bundle 部署为目录(而不是存档)。但是,如果您必须处理需要使用 File
的遗留库,这会很有帮助。对象。要转换为文件,您不能使用 URL.getPath()
方法,因为 Equinox 有自己的 URL 格式。您应该使用 org.eclipse.core.runtime.FileLocator
类解析为 File
. FileLocator.getBundleFile(Bundle)
做你想要的。 关于file - 无法访问 bundle 资源/文件 (OSGi),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6244993/