Reading resources from a Eclipse plugin

less than 1 minute read

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.

Updated: