背景
项目中经常会遇到需要加载类路径下面的一些资源文件。这里记录一个读取指定路径下 sql 文件的例子,其他场景自己参考修改~~~
private static final String SQL_LOCATION = "META-INF/db.sql";
private void loadResource(String sqlFile) throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
InputStream sqlFileIn = null;
try {
URL url = classLoader.getResource(sqlFile);
if (url == null) {
throw new RuntimeException("can not get sql file[" + sqlFile + "]");
}
sqlFileIn = url.openStream();
StringBuilder sb = new StringBuilder();
byte[] buff = new byte[1024];
int byteRead = 0;
while ((byteRead = sqlFileIn.read(buff)) != -1) {
sb.append(new String(buff, 0, byteRead, "UTF-8"));
}
List<String> sqlList = new ArrayList<>();
String[] sqlArr = sb.toString().split(";");
for (int i = 0; i < sqlArr.length; i++) {
if (StringUtils.isNotEmpty(sqlArr[i])) {
sqlList.add(sqlArr[i]);
}
}
System.out.println(sqlList);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (sqlFileIn != null) {
sqlFileIn.close();
}
}
}
网友评论