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("failed to copy local source template", 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("failed to copy jar source template", 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("failed to close jarFile", e);
            }
        });
    }
}   
載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。