开发过程中有时会把文件打包入jar包里,如果要读取文件内容,直接使用地址是会报错。
可以通过文件流方式读取。
废话不多说上代码,引用hutool工具
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.io.resource.Resource;
import cn.hutool.core.util.StrUtil;
public List<String> getSql(TaskConfigEnum taskConfigEnum) {
String path = BASE_CLASSPATH + "test.sql";
Resource resource = new ClassPathResource(path);
InputStream inputStream = null;
List<String> sqlList;
try {
inputStream = resource.getStream();
String content = IoUtil.readUtf8(inputStream);
sqlList = StrUtil.splitTrim(content, ";");
}catch (Exception e){
throw new RuntimeException("运行时异常"+e);
}finally {
try {
if(inputStream != null){
inputStream.close();
}
}catch (Exception e) {
throw new RuntimeException("关闭资源失败"+e);
}
}
return sqlList;
}