8

该方法FileLocator.resolve(url)可用于将地址转换bundleentry://something/somewhere/x.txt/mnt/foo/somewhere/x.txt.

但是,这也记录在https://bugs.eclipse.org/bugs/show_bug.cgi?id=145096中,URL 没有转义。例如,如果包含引用包的 Eclipse 安装位于包含空格的目录中,则返回的 URLFileLocator.resolve仍然包含空格,因此调用url.toURI()失败。

  • 如何手动转义URL 中的所有必要字符?
  • 如何File根据相对于当前包的路径获取对象?

作为参考,如果该文件位于包含空格的目录中,则尝试dir在我的插件文件中查找目录时失败的代码如下:.jar

    final IPath pathOfExampleProject = new Path("dir");
    final Bundle bundle = Platform.getBundle(AproveIDs.PLUGIN_ID);
    final URL url = FileLocator.find(bundle, pathOfExampleProject, null);
    final URL url2 = FileLocator.toFileURL(url);
    url2.toURI(); // Illegal character in path at index [...]
4

3 回答 3

7

我刚刚找到了这段代码:

http://code.google.com/p/dart/source/browse/branches/bleeding_edge/dart/editor/tools/plugins/com.google.dart.tools.core/src/com/google/dart/tools/核心/内部/模型/BundledSystemLibrary.java?r=2057

相关行确实有帮助:

// We need to use the 3-arg constructor of URI in order to properly escape file system chars.
URI resolvedUri = new URI(resolvedUrl.getProtocol(), resolvedUrl.getPath(), null);
于 2013-02-03T20:50:14.870 回答
1

两个附加说明:

  • FileLocator.resolve 确实解析了一个 URL,但它不一定返回一个 file:/ URL。在打包捆绑包的默认情况下(在 .jar 中),您应该使用 FileLocator.toFileURL,它会在需要时自动将资源提取到缓存中。
  • 由于 Eclipse 4.x 现在默认包含 EMF Common API,您可以使用 EMF 的 URI API 更简单地转义 URL,如下所示:

URI resolvedUri = URI.createFileURI(resolved.getPath());

要获取文件名,请调用resolvedUri.toFileString();

于 2014-10-27T16:18:23.923 回答
0

来自Vogella 博客:

URL url;
try {
    url = new 
    URL("platform:/plugin/de.vogella.rcp.plugin.filereader/files/test.txt");
    InputStream inputStream = url.openConnection().getInputStream();
    BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
    String inputLine;

while ((inputLine = in.readLine()) != null) {
    System.out.println(inputLine);
}

in.close();

} catch (IOException e) {
    e.printStackTrace();
}

要获取 URL,可以使用以下方法:

Bundle thisBundle = FrameworkUtil.getBundle(getClass());
URL fileURL = thisBundle.getEntry("<relative_file_path_from_project_root");

此外,可以选择 Stream/Reader 的类型来读取图像/文本。

于 2018-05-08T13:19:38.550 回答