spingboot打成jar之后,读取不到相对路径。eg.Resource下文件
在本地项目启动的时候,可以使用AttachmentUtil.class.getClassLoader().getResource(path);读取到文件。
但是项目打成jar之后,读取不到文件。会报错java.io.FileNotFoundException
主要原因是springboot内置tomcat,打包后是一个jar包,因此通过文件读取获取流的方式行不通,因为无法直接读取压缩包中的文件,读取只能通过流的方式读取。
ClassPathResource classPathResource = new ClassPathResource(path);
InputStream inputStream =classPathResource.getInputStream();
1.当你要将文件内容读取成字符串时
/**
* 读取指定路径的模板文件为String
*/
public String getTemplateHtmlString(String path) throws IOException {
ClassPathResource classPathResource = new ClassPathResource(path);
InputStream inputStream =classPathResource.getInputStream();
if (inputStream == null) {
throw new GeneralBusinessException("找不到html模板!");
}
try {
StringBuilder builder = new StringBuilder();
InputStreamReader reader = new InputStreamReader(inputStream , "UTF-8" );
BufferedReader bfReader = new BufferedReader( reader );
String tmpContent = null;
while ( ( tmpContent = bfReader.readLine() ) != null ) {
builder.append( tmpContent );
}
bfReader.close();
return builder.toString() ;
} catch ( UnsupportedEncodingException e ) {
log.error("Files.toString出错!", e);
return null;
}
}
2.当直接读取流到文件中
/**
* 利用表单域生成pdf
* @param templatePath 模板路径
* @param replacement pdf中存放的数据
*/
public static byte[] createPdf(String templatePath, Object replacement){
try {
ClassPathResource classPathResource = new ClassPathResource(templatePath);
InputStream inputStream =classPathResource.getInputStream();
/* 打开已经定义好字段以后的pdf模板 */
PdfReader reader = new PdfReader(inputStream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfStamper stamp = new PdfStamper(reader,baos);
/* 使用中文字体 */
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
BaseFont.NOT_EMBEDDED);
Font FontChinese = new Font(bf, 12, Font.NORMAL);
/* 取出报表模板中的所有字段 */
AcroFields form = stamp.getAcroFields();
form.addSubstitutionFont(bf);
for (Field aField : replacement.getClass().getDeclaredFields()) {
String fieldName = aField.getName();
if ("class java.lang.String".equals(aField.getGenericType().toString())) {
Method method = replacement.getClass().getMethod("get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1));
String fieldValue = (String) method.invoke(replacement);
if (fieldValue != null) {
form.setField(fieldName,fieldValue);
}
}
}
/* 如果为false那么生成的PDF文件还能编辑,一定要设为true*/
stamp.setFormFlattening(true);
stamp.close();
reader.close();
baos.close();
return baos.toByteArray();
}catch(Exception e){
e.printStackTrace();
}
return null;
}
3.SpringBoot读取Resource下文件的几种方式
方法一:(推荐:本地和打成jar都可以读取到)
ClassPathResource classPathResource = new ClassPathResource(templatePath);
InputStream inputStream =classPathResource.getInputStream();
方法二:(推荐:本地不可以,打成jar都可以读取到)
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("excleTemplate/test.xlsx");