//classpath加载文件
private static File getCardExcelFile(String path) {
try {
return new File(URLDecoder.decode(Thread.currentThread().getContextClassLoader().getResource(path).getPath(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
return null;
}
}
注意 :
1、参数path:是相对路径 。如下: File cardExcelFile = getCardExcelFile("template/weekTemplate.docx");
2、因为方法获取文件是从target目录下获取的,所以需要打包后才能读取到文件。
3、打包过后注意文件是否被损坏,例如word、excel 等。
4、如果损坏了,可以通过maven去排除编译时文件
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<nonFilteredFileExtensions>
<nonFilteredFileExtension>docx</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
</plugin>