原文:http://blog.vogella.com/2010/07/06/reading-resources-from-plugin/
经常我们会把一些静态资源存放在bundle里,如何读取bundle里的资源呢?
1. Platform.getBundle(…)
de.vogella.example.readfile是plug-in ID。
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(); }
2. 直接使用URL
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(); }
总结
第二种方法更好,dependency更干净,不用使用Platform类和Bundle类。