访问资源的相对文件路径 [英] Relative filepath to access resources

查看:55
本文介绍了访问资源的相对文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Eclipse 4、RCP 和 SWT 很陌生,我一直在解决这个问题:我想从具有相对文件路径的代码访问图像资源.问题是默认位置 ./ 设置为我的主目录 /home/name/ (我使用的是 Ubuntu).我发现通过创建一个新文件并打印其 CanonicalPath.

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.

我习惯于将默认位置设置为项目目录,例如 /home/name/workspace/project/,这是我目前看到的默认位置Eclipse/java 程序中的行为.

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

注意:我标记了 e4、rcp 和 swt,因为我不确定是哪一个导致了差异.

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

推荐答案

在 Eclipse 插件(包括 RCP 代码)中,您应该使用 FileLocator 类来查找插件中的资源.

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

你也可以使用FileLocator.find:

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

URL fileUrl = FileLocator.toFileURL(url);

不要忘记在 build.properties 中包含您的资源目录.

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.

在 e4 插件中,您可以使用 @OSGiBundle 注入 Bundle:

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

@Inject
@OSGiBundle
Bundle bundle;

(@OSGiBundle 需要依赖于 org.eclipse.e4.core.di.extensions 插件).

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

这篇关于访问资源的相对文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆