讀取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("未找到文件");
}