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:

[sourcecode lang=”java”]

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();
}
[/sourcecode]

Alternatively you can also use URL directly. I have to thank Paul Webster for this tip.

[sourcecode lang=”java”]

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();
}
[/sourcecode]

I believe the second option is the better one, as you avoid a dependency to the class Platform.

About Lars Vogel

Lars Vogel is the founder and CEO of the vogella GmbH and works as Eclipse and Android consultant, trainer and book author. He is a regular speaker at international conferences, He is the primary author of vogella.com. With more than one million visitors per month this website is one of the central sources for Java, Eclipse and Android programming information.
This entry was posted in Eclipse and tagged . Bookmark the permalink.

6 Responses to Reading resources from a Eclipse plugin

Comments are closed.