之前的代码如下:
ActiveRecordPlugin activeRecordPlugin = new ActiveRecordPlugin(sourceEnum.name().toLowerCase(), plugin); activeRecordPlugin.setBaseSqlTemplatePath(PathUtils.getRootPath()); activeRecordPlugin.addSqlTemplate("sql/xjq_weibo.sql");
修改代码如下:
ActiveRecordPlugin activeRecordPlugin = new ActiveRecordPlugin(sourceEnum.name().toLowerCase(), plugin); //这行不要 //activeRecordPlugin.setBaseSqlTemplatePath(PathUtils.getRootPath()); activeRecordPlugin.getEngine().setSourceFactory(new ClassPathSourceFactory()); activeRecordPlugin.addSqlTemplate("sql/xjq_weibo.sql");
这里用到了ClassPathSource,可以从jar文件中读取文件。
默认是用FileSource,这个是用File file = new File()方式读取文本文件。
而读jar包里的文件时,用了ClassPathSource,看源码可以发现,用的是(贴几行关键代码)
InputStream inputStream = classLoader.getResourceAsStream(finalFileName); StringBuilder ret = new StringBuilder(); BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(inputStream, encoding)); // br = new BufferedReader(new FileReader(fileName)); String line = br.readLine(); if (line != null) { ret.append(line); } else { return ret; } while ((line=br.readLine()) != null) { ret.append('\n').append(line); } return ret; } catch (Exception e) { throw new RuntimeException(e); }
牛逼!
感谢你的分享