banner
Matt

Matt

Matt-xlog
telegram
github

【JAVA】【工具类】运行时读取jar包内文件复制到文件夹下

import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.AbstractMap;
import java.util.List;
import java.util.Map;
import java.util.jar.JarFile;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.net.URI;
/**
 * 读取复制jar包文件内容工具类
 */
public class readJarUtils {
    private static final Logger logger = LoggerFactory.getLogger(readJarUtils.class);
    public void test(){
        URI uri = null;
        try {
            uri = readJarUtils.class.getProtectionDomain().getCodeSource().getLocation().toURI();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        String tempPath = "/deployments";
        String sourceDir = "krb";  //资源文件夹
        if (uri.toString().startsWith("file")) {
            // IDEA运行时,进行资源复制
            copyLocalResourcesFileToTemp(sourceDir + "/", "*", tempPath + "/" + sourceDir);
        } else {
            // 获取jar包所在路径
            String jarPath = uri.toString();
            uri = URI.create(jarPath.substring(jarPath.indexOf("file:"),jarPath.indexOf(".jar") + 4));
            // 打成jar包后,进行资源复制
            readJarUtils.copyJarResourcesFileToTemp(uri, tempPath, "BOOT-INF/classes/" + sourceDir);
        }

    }
/**
     * 复制本地资源文件到指定目录
     * @param fileRoot      需要复制的资源目录文件夹
     * @param regExpStr     资源文件匹配正则,*表示匹配所有
     * @param tempParent    保存地址
     */
    public static void copyLocalResourcesFileToTemp(String fileRoot, String regExpStr, String tempParent) {
        try {
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = 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 e) {
                    // 如果resource为文件夹时,会报异常,这里直接忽略这个异常
                }
                if (stream == null) {
                    newFile.mkdirs();
                    copyLocalResourcesFileToTemp(fileRoot + resource.getFilename()  + "/", regExpStr, tempParent + "/" + resource.getFilename());
                } else {
                    if (!newFile.getParentFile().exists()) {
                        newFile.getParentFile().mkdirs();
                    }
                    org.apache.commons.io.FileUtils.copyInputStreamToFile(stream, newFile);
                }
            }
        } catch (Exception e) {
            logger.error("复制本地源模板失败", e);
        }
    }
/**
     * 复制jar包中的资源文件到指定目录
     * @param path          jar包所在路径
     * @param tempPath      保存目录
     * @param filePrefix    需要进行复制的资源文件目录:以BOOT-INF/classes/开头
     */
    public static void copyJarResourcesFileToTemp(URI path, String tempPath, String filePrefix) {
        try {
            List<Map.Entry<ZipEntry, InputStream>> collect =
                    readJarFile(new JarFile(path.getPath()), filePrefix).collect(Collectors.toList());
            for (Map.Entry<ZipEntry, InputStream> entry : collect) {
                // 文件相对路径
                String key = entry.getKey().getName();
                // 文件流
                InputStream stream = entry.getValue();
                File newFile = new File(tempPath + key.replaceAll("BOOT-INF/classes", ""));
                if (!newFile.getParentFile().exists()) {
                    newFile.getParentFile().mkdirs();
                }
                org.apache.commons.io.FileUtils.copyInputStreamToFile(stream, newFile);
            }
        } catch (IOException e) {
            logger.error("复制jar源模板失败", e);
        }
    }
 @SneakyThrows
    public static Stream<Map.Entry<ZipEntry, InputStream>> readJarFile(JarFile jarFile, String prefix) {
        Stream<Map.Entry<ZipEntry, InputStream>> readingStream =
                jarFile.stream().filter(entry -> !entry.isDirectory() && entry.getName().startsWith(prefix))
                        .map(entry -> {
                            try {
                                return new AbstractMap.SimpleEntry<>(entry, jarFile.getInputStream(entry));
                            } catch (IOException e) {
                                return new AbstractMap.SimpleEntry<>(entry, null);
                            }
                        });
        return readingStream.onClose(() -> {
            try {
                jarFile.close();
            } catch (IOException e) {
                logger.error("关闭jarFile失败", e);
            }
        });
    }
}   
加载中...
此文章数据所有权由区块链加密技术和智能合约保障仅归创作者所有。