代码实现 jar包解压缩

109 阅读1分钟

解压缩jar包

@Slf4j
public class JarUtils {

    /**
     * 解压缩jar包
     * @param jarFile
     * @param outputDir
     * @throws IOException
     */
    private static Boolean unzipJar(File jarFile, File outputDir)  {
        Boolean result = Boolean.TRUE;
        JarFile jar = null;
        try {
            jar = new JarFile(jarFile);
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                File entryFile = new File(outputDir, entry.getName());
                if (entry.isDirectory()) {
                    entryFile.mkdirs();
                } else {
                    File parent = entryFile.getParentFile();
                    if (parent != null && !parent.exists()) {
                        parent.mkdirs();
                    }
                    InputStream inputStream = null;
                    FileOutputStream outputStream = null;
                    try {
                        inputStream = jar.getInputStream(entry);
                        outputStream = new FileOutputStream(entryFile);
                        byte[] buffer = new byte[1024];
                        int bytesRead;
                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }
                    } finally {
                        closeStream(inputStream);
                        closeStream(outputStream);
                    }
                }
            }
        }catch (Throwable e){
            log.error("JarUtils.unzipJar Exception ",e);
            result = Boolean.FALSE;
        }finally {
            closeStream(jar);
        }
        return result;
    }

    /**
     * 关闭流
     * @param closeable
     */
    public static void closeStream(Closeable closeable){
        if(Objects.nonNull(closeable)){
            try {
                closeable.close();
            } catch (Throwable e) {
                log.error("JarUtils.closeStream Excepton ",e);
            }
        }

    }
}