Accessing resource files within your Eclipse plugins

Posted by Mike Haller on Friday, December 29. 2006 at 00:00 in Eclipse
Sometimes, especially in the development phase, you want to get your Eclipse Plugin's absolute file system location on the disk. Usually, you want to have a java.io.File. Since Eclipse mainly uses URLs to locate resources, it's not an easy one-liner to get the location. However, the utility class org.eclipse.core.runtime.FileLocator comes to the rescue:

URL bundleRoot = getBundle().getEntry("/");
URL fileURL = FileLocator.toFileURL(bundleRoot);
java.io.File file = new java.io.File(fileURL.toURI());

System.out.println("Bundle location:" + file.getAbsolutePath());


Note: please be aware that your plugin should be normally packaged as jar file and thus the above code does not work any more in a packaged deployment! To get this working, you must set the unpack attribute in your feature for the plugin.

What you really want to do is to use getBundle().getEntry("/file.txt").openStream() to get the contents of a file which is located within your plugin.

The code above is called from within a Plugin Activator class and uses the shortcut getBundle() method. If you need the code outside of an Activator class, use the Platform to resolve the bundle first. A one-liner looks like this:

new File(FileLocator.toFileURL(Platform.getBundle(
     pluginId).getEntry("/")).toURI());




Add Comment

Enclosing asterisks marks text as bold (*word*), underscore are made via _word_.
Standard emoticons like :-) and ;-) are converted to images.
E-Mail addresses will not be displayed and will only be used for E-Mail notifications
 
 

About

My name is Mike Haller and I'm a software developer and architect at Bosch Software Innovations in Germany. I love programming, playing games and reading books. I like good food, making photos and learning and mentoring about the craftsmanship of commercial software development. Stack Overflow profile for mhaller

Quicksearch