How to read a file included in a bundle
The following method reads currency codes from a text file using a FileLocator. In this example I look for the file in the default bundle, but you can access other bundles through the Platform object.
The Eclipse classes involved in this operation are:
org.eclipse.core.runtime.FileLocator
org.eclipse.core.runtime.IPath
org.eclipse.core.runtime.Path
org.osgi.framework.Bundle
public static String[] codeArray() {
String line;
ArrayList codeList = new ArrayList();
Bundle bundle = Activator.getDefault().getBundle();
// or bundle = Platform.getBundle("yourBundleIDHere");
IPath path = new Path("/data/currency.txt"); // from plugin root
try {
//get stream using the FileLocator
InputStream stream = FileLocator.openStream(bundle, path, false);
// create a buffered reader
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
//read the file
while((line = reader.readLine()) != null){
codeList.add(line);
}
}
catch (IOException ioe) {
System.err.print(ioe.getMessage());
ioe.printStackTrace(System.err);
}
//Extract array, sort, return
String[] array = codeList.toArray(new String[0]);
Arrays.sort(array);
return array;
}