读取jar包中resources文件夹下的文件,会报找不到的错误,原因在网上找了,没看懂,下面是解决方法
public static File getJarResourceFile(){
//获取容器资源解析器
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try {
//获取所有匹配的文件
Resource[] resources = resolver.getResources("resources文件夹下的文件路径");
if (resources.length > 0) {
//获得文件流,因为在jar文件中,不能直接通过文件资源路径拿到文件,但是可以在jar包中拿到文件流
InputStream stream = resources[0].getInputStream();
if (log.isInfoEnabled()) {
log.info("读取的文件流 [" + stream + "]");
}
String targetFilePath = System.getProperty("user.home") + File.separator + resources[0].getFilename();
if (log.isInfoEnabled()) {
log.info("放置位置 [" + targetFilePath + "]");
}
File ttfFile = new File(targetFilePath);
//把流中的数据写入到文件中
InputStream initialStream = stream;
byte[] buffer = new byte[initialStream.available()];
initialStream.read(buffer);
OutputStream outStream = new FileOutputStream(ttfFile);
outStream.write(buffer);
initialStream.close();
outStream.close();
return ttfFile;
}
} catch (IOException e) {
if (log.isWarnEnabled()) {
log.warn("读取文件流失败,写入本地库失败! " + e);
}
}
throw new RuntimeException("未找到文件");
}