package com.gradle

import java.util.jar.JarEntry
import java.util.jar.JarFile
import java.util.jar.JarOutputStream

/**
 * Created by glen on 2016/9/2.
 * modify by glen
 */
public class JarZipUtil {

    /**
     * 将该jar包解压到指定目录
     * @param jarPath jar包的绝对路径
     * @param destDirPath jar包解压后的保存路径
     */
    public static void unzipJar(File jar, String destDirPath) {
        JarFile jarFile = new JarFile(jar.absolutePath)
        Enumeration<JarEntry> jarEntryIterator = jarFile.entries()
        while (jarEntryIterator.hasMoreElements()) {
            JarEntry jarEntry = jarEntryIterator.nextElement()
            if (jarEntry.directory) {
                continue
            }
            String outFileName = destDirPath + "/" + jarEntry.getName()
            File outFile = new File(outFileName)
            outFile.getParentFile().mkdirs()
            InputStream inputStream = jarFile.getInputStream(jarEntry)
            FileOutputStream fileOutputStream = new FileOutputStream(outFile)
            fileOutputStream << inputStream
            fileOutputStream.close()
            inputStream.close()
        }
        jarFile.close()
    }

    /**
     * 重新打包jar
     * @param packagePath 将这个目录下的所有文件打包成jar
     * @param destPath 打包好的jar包的绝对路径
     */
    public static void zipJar(String packagePath, File jar) {
        jar.deleteOnExit()
        JarOutputStream zos = new JarOutputStream(new FileOutputStream(jar.absolutePath))
        zipFile(new File(packagePath), zos, "")
        zos.close()
    }

    private static void zipFile(File inFile, JarOutputStream out, String dir) {
        if (inFile.isDirectory()) {
            File[] fl = inFile.listFiles()
            out.putNextEntry(new JarEntry(dir + "/"))
            dir = dir.length() == 0 ? "" : dir + "/"
            for (int i = 0; i < fl.length; i++)
                zipFile(fl[i], out, dir + fl[i].getName())
        } else {
            out.putNextEntry(new JarEntry(dir))
            FileInputStream ins = new FileInputStream(inFile)
            out << ins
            ins.close()
        }
    }
}
