欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot 读取 jar包下resource中整个文件夹下内容,生成临时目录 博客分类: java springbootjarresources 

程序员文章站 2024-03-21 19:28:34
...

static {
    try {
       copytReeourcesFileToTemp("classpath:static/xxx/", "*", System.getProperty("java.io.tmpdir") + "tempspring");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
public static void copytReeourcesFileToTemp(String fileRoot, String regExpStr, String tempParent) throws Exception {
try {
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = (Resource[]) resolver.getResources(fileRoot + regExpStr);
for (Resource resource : resources) {File newFile = new File(tempParent, resource.getFilename());
if (newFile.exists()) {
newFile.delete();
}
InputStream stream = null;
try {
stream = resource.getInputStream();
} catch (Exception e1) {
logger.debug(resource.getFilename() + "是文件夹");
}
if (stream == null) {logger.debug("创建文件夹" + resource.getFilename());
newFile.mkdirs();
Resource[] children = (Resource[]) resolver.getResources(fileRoot + resource.getFilename() + "/" + regExpStr);
for (Resource child : children) {
copytReeourcesFileToTemp(fileRoot + resource.getFilename() + "/", regExpStr, tempParent + "\\" + resource.getFilename());
}
} else {

if (!newFile.getParentFile().exists()) {
newFile.getParentFile().mkdir();
}
FileUtils.copyInputStreamToFile(stream, newFile);
}
}
} catch (Exception e) {
System.out.println("复制文件出现错误" + e.getMessage());
throw e;
}

}