Feb 19, 2007

Finding the Install Location of a Plugin

Usually a plugin should not depend on its location. In rare cases we may have to find the location of the plugin to load some resources. But there is no standard API to get the plugin's installed location. This tips explains you to add one.

This can be done with just four lines of code. Add this In the Activator class of your plugin.

public String getInstallLocation() throws Exception {

Bundle bundle = getBundle();
URL locationUrl =
FileLocator.find(bundle,new Path("/"), null);
URL fileUrl =
FileLocator.toFileURL(locationUrl);
return fileUrl.getFile();
}

If your want this method outside your Activator class, you need replace the first line with this:

Bundle bundle = Platform.getBundle("com.example.plugin.id");

The first line, is to get the bundle. The second line gives you the url of the location. This URL is an Eclipse specific relative URL with bundle id. You need to resolve it to get a "file://" URL. That is done in the third done. The forth line, converts it into a String.

1 comments:

Nitin Dahyabhai said...

Using Bundle.getEntry(String) is safer and will return a URL directly to the resource in question. Remember, the file's not as important as its contents, and you can open an input stream on that URL.