FileLocator.resolve(url)的转义结果

问题描述 投票:8回答:3

方法FileLocator.resolve(url)可用于将地址bundleentry://something/somewhere/x.txt转换为/mnt/foo/somewhere/x.txt的正确文件URL。

但是,https://bugs.eclipse.org/bugs/show_bug.cgi?id=145096也记录了该URL,URL未被转义。例如,如果包含引用的bundle的Eclipse安装位于包含空格的目录中,则FileLocator.resolve返回的URL仍包含空格,因此调用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 [...]
eclipse eclipse-plugin
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/core/internal/model/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);

1
投票

另外两个说明:

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

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

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


0
投票

来自Vogella Blog:

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的类型来读取图像/文本。

© www.soinside.com 2019 - 2024. All rights reserved.