Reading resources from a Eclipse plugin
Frequenty you want to store static files in your bundle and load them from your bundle. For this you can use the following code, of course replace the bundle id with your version:
Bundle bundle = Platform.getBundle("de.vogella.example.readfile");
URL fileURL = bundle.getEntry("files/test.txt");
File file = null;
try {
file = new File(FileLocator.resolve(fileURL).toURI());
} catch (URISyntaxException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
Alternatively you can also use URL directly. I have to thank Paul Webster for this tip.
URL url;
try {
url = new URL("platform:/plugin/de.vogella.rcp.plugin.filereader/files/test.txt");
InputStream inputStream = url.openConnection().getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
I believe the second option is the better one, as you avoid a dependency to the class Platform.
July 6th, 2010 at 4:31 am
Great tip! Thank you! Every time I’ve tried to do this in the past, it’s been a huge pain and I’ve usually resorted to writing code that just seems messy and left me thinking “there has to be a better way to do this.” Here are two better ways — thanks!
July 6th, 2010 at 6:48 am
Hi Lars,
The second option is really much more reliable!
I’ve done something quite similar a week or two ago where I stumbled over the first method, when the file was bundled within the plugin jar.
The problem was: The files in question where somthing I called resource-jars – that means they where jars itself… That made me loads of trouble.
The final idea was there:
1) create an “resource” extension point
2) load the urls into a URLClassLoader
3) retrieve the resources from within the URClassLoader via theire specific class loader dependent URL
It works, but it still have the look of a major quick hack
Greetings,
Daniel
July 6th, 2010 at 8:33 am
@Chris: Thanks for the feedback
@dzim: I agree with you that the second method is the better one.
July 6th, 2010 at 9:30 am
Both of these are Eclipse-specific, of course. It’s actually a lot better/easier to use Class.getResourceAsStream() to pull the bytes out, which has the advantage of working across all OSGi systems and outside of OSGi too. Plus it uses the bundle of wherever the class was loaded from.
There is a bug in PDE (don’t have the ID but it wa
July 6th, 2010 at 9:32 am
… was filed by me and says “getEntry and getResource inconsistent”) – basically, at runtime, bundle.getEntry and bundle.getResource load the same; but under PDE, resources are loaded from the root of your plugin whilst resources come from under the /bin or /classes directory. I don’t believe that’s fixed
July 6th, 2010 at 9:37 am
@Alex at least you don’t need to import Eclipse classes in the second approach which I believe is better.