Relative filepath to access resources

末鹿安然 提交于 2019-12-12 03:24:37

问题


I am quite new to Eclipse 4, RCP and SWT and I am stuck on this issue : I want to access image resources from code with a relative filepath. Problem is that the default location ./ is set to my home directory /home/name/ (I'm using Ubuntu). I have found that by creating a new File and printing its CanonicalPath.

I am used to having the default location set to the project directory, such as /home/name/workspace/project/, which is, from what I've seen so far, the default behavior in Eclipse / java programs.

I would like to keep this behavior because it seems more reliable to me (after deployment for example).

Note: I have tagged e4, rcp and swt because I'm not sure which one causes the difference.


回答1:


In an Eclipse plugin (including RCP code) you should use the FileLocator class to find resources within the plugin.

You open a resource as a stream:

Bundle bundle = ... plugin bundle

IPath path = new Path("path relative to plugin root");

InputStream is = FileLocator.openStream(bundle, path, true);

You can also use FileLocator.find:

URL url = FileLocator.find(bundle, path, null);

URL fileUrl = FileLocator.toFileURL(url);

Don't forget to include your resources directory in the build.properties.

If your image is not in the plugin you can't really use relative paths.

In an e4 plugin you can inject the Bundle using @OSGiBundle:

@Inject
@OSGiBundle
Bundle bundle;

(@OSGiBundle requires a dependency on the org.eclipse.e4.core.di.extensions plugin).



来源:https://stackoverflow.com/questions/38431616/relative-filepath-to-access-resources

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!