Tuesday, March 3, 2009

Getting access to files in Eclipse plug-ins

There are several ways to access files in Eclipse. Here are some samples
  • Getting an ImageDescriptor from a plug-in
  • Getting a resolved URL to a resource in another plug-in
  • Opening a resource in an editor

Getting an ImageDescriptor from a plug-in

You can get an image descriptor to an image resource via the
  • UIPlugin.imageDescriptorFromPlugin("pluginId", "icons/image.png")

Getting a URL to a resource inside a plug-in
First you have to have a plug-in (Bundle). Your can get it via
  • Activator.getDefault().getBundle() or
  • Platform.getBundle("plug-in id")

//If you want to access your own plug-in use Activator.getDefault().getBundle()

Bundle bundle = Platform.getBundle("org.eclipse.ui");

// This line return a url looking like this, bundleentry://921/plugin.xml
URL url = bundle.getEntry("/plugin.xml");

try {
// This line resolves the bundle resource url to an explicit file url into the bundle
// The url will get to look like below,
// jar:file:C:\...\org.eclipse.ui_3.4.0.I20080610-1200.jar!/plugin.xml
URL realUrl = FileLocator.resolve(url);

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


Opening a resource in an editor
Here is a sample on how to open the org.eclipse.ui plugin.xml in an editor.

// Start by getting an IPath to a bundle resource.
IPath path = null;
URL url = null;
try {
url = FileLocator.toFileURL( Platform.getBundle("org.eclipse.ui").getEntry("/plugin.xml"));
path = new Path(url.getPath());
} catch (IOException e) {

e.printStackTrace();
}

// Next, use the Eclipse file store to validate and pass to an editor
IFileStore fileStore = EFS.getLocalFileSystem().getStore(path);

if (!fileStore.fetchInfo().isDirectory() && fileStore.fetchInfo().exists()) {

IWorkbenchPage page = getSite().getPage();
try {
IDE.openEditorOnFileStore(page, fileStore);
} catch (PartInitException e) {
e.printStackTrace();
}
}

No comments:

Search This Blog

Eclipse Live: Equinox Ganymede

The creator of an Eclipse Bible, introduces Equinox and its building blocks for creating applications. We overview the architecture and technology, and demonstrate many of the building blocks.
by Jeff McAffer (Code 9)