当我们需要读取Jar包内的文件时,我们就不能使用
来读取了,因为根本无法指定这个filePath,如果说在开发时,还可以利用
- new File(filePath)
来获得文件路径,那么当打成Jar包是,路径就不存在了。
- this.getClass().getResource()
这是我们要读取文件,就需要用流的形式了,我们需要利用
方法,以流的形式拿到Jar包中的文件:
- this.getClass().getResourceAsStream
- InputStream is = this.getClass().getResourceAsStream(
- "/templates/TemplateDO.ja");
- BufferedReader br;
- StringBuilder strBlder = new StringBuilder("");
- try {
- br = new BufferedReader(new InputStreamReader(is));
- String line = "";
- while (null != (line = br.readLine())) {
- strBlder.append(line + "\n");
- }
- br.close();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return strBlder.toString();
来源: http://www.phpxs.com/code/1002553/