如何从 Eclipse 插件获取资源路径

How to get resources path from an Eclipse plugin

我正在使用 Eclipse Plugin-in-project 开发一个 Eclipse 插件,它将在工具栏中添加一个菜单项。

我的插件项目依赖于同一个插件项目中的一个文件,我需要该文件的路径。

下面是我用来获取路径的示例代码:

Bundle bundle = Platform.getBundle("com.feat.eclipse.plugin");
URL fileURL = bundle.getEntry("webspy/lib/file.txt");
File file = null;
String path=null;
try {
    file = new File(FileLocator.resolve(fileURL).toURI());
    path = file.getAbsolutePath();
} catch (URISyntaxException e1) {
    e1.printStackTrace();
} catch (IOException e1) {
    e1.printStackTrace();
}

While 运行 from Eclipse 运行 as > Eclipse Application 它给了我正确的路径。但是当我将我的插件导出为 jar 并将其添加到我的 Eclipse 插件文件夹时,它没有给我正确的路径。

请帮我解决这个问题!

jar 中的文件没有 java.io.File,因为它们在 JAR 文件中。

您可能希望FileLocator.openStream(...)读取文件内容。

如果你真的想要一个java.io.File,那么你可以考虑使用Eclipse EFS及其IFileStore.toLocalFile(...)为你解压文件到一个临时目录。 EFS.getStore(fileURL).toLocalFile(EFS.CACHE, null) 之类的东西应该做你想做的,但请记住,这会将文件放在临时目录中,并在 Eclipse 退出时将其删除。

使用:

URL url = FileLocator.find(bundle, new Path("webspy/lib/file.txt"), null);

url = FileLocator.toFileURL(url);

File file = URIUtil.toFile(URIUtil.toURI(url));

当您的文件打包到 jar 中时,FileLocator.toFileURL 会将它们复制到一个临时位置,以便您可以使用 File.

访问它们