-->

Relative filepath to access resources

2019-09-10 08:01发布

问题:

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).



标签: java swt rcp e4