Java로 jar 압축풀기

jar 압축을 푸는 예제이다.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;

public class JarUtil {

    private static final int BUFFER = 8196;

    public static boolean extract(String jarfilename, String dest) {
        File jarfile = new File(jarfilename);

        if (!jarfile.exists()) {
            System.out.println("Jar File does not exist!");
            return false;
        }

        File destfile = new File(dest);
        if (!destfile.exists()) {
            if (!destfile.mkdir()) {
                System.out.println(dest + " directory make failed.");
                return false;
            }
        }

        boolean result = false;
        JarInputStream jis = null;
        FileOutputStream fos = null;
        try {
            jis = new JarInputStream(new FileInputStream(jarfile));

            File tmpDir = new File(dest + "META-INF");
            tmpDir.mkdir();
            File tmpFile = new File(dest + "META-INF/MANIFEST.MF");
            Manifest manifest = jis.getManifest();
            fos = new FileOutputStream(tmpFile);
            manifest.write(fos);
            fos.close();

            JarEntry entry = null;
            while ((entry = jis.getNextJarEntry()) != null) {
                String destFile = dest + entry.getName();
                if (entry.isDirectory()) {
                    if (!new File(destFile).mkdir())
                        System.out.println(destFile + " directory make failed.");
                    continue;
                }

                fos = new FileOutputStream(dest + entry.getName());
                byte data[] = new byte[BUFFER];
                int count;
                while ((count = jis.read(data, 0, BUFFER)) != -1) {
                    fos.write(data, 0, count);
                }
                System.out.println(destFile);
            }
            result = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (jis != null)
                    jis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}



최종 수정 : 2021-08-27