Java Programming

Java 파일내에서 Jar파일의 압축을 해제하는 Sample

tomato13 2008. 12. 8. 19:29
http://haewoo.springnote.com/pages/27010

public class JarExtractSample {
    /**
     * @param args
     * @throws IOException
     * @throws FileNotFoundException
     */
    public static void main(String[] args) throws FileNotFoundException, IOException {
        String filename = "F_AC_AR1.jar";
        String dest = "./AAA/";
        File file = new File(filename);
        if (file.exists()) {
            System.out.println("OK");
        } else {
            System.out.println("Jar File does not exist!");
            System.exit(0);
        }
        File destD = new File(dest);
        if (!destD.exists()) {
            if (destD.mkdir()) {
                System.out.println(dest + " 디렉토리 생성!!");
            } else {
                System.out.println(dest + " 디렉토리 생성실패!!");
                System.exit(0);
            }
        }
        JarInputStream jis = new JarInputStream(new FileInputStream(filename));
        // META-INF 정보를 저장하기 위한 처리
        File tmpD = new File(dest + "META-INF");
        tmpD.mkdir();
        File tmpFile = new File(dest + "META-INF/MANIFEST.MF");
        Manifest manifest = jis.getManifest();
        FileOutputStream fos = new FileOutputStream(tmpFile);
        manifest.write(fos);
        fos.close();
        JarEntry entry = null;
        // Jar File의 파일 정보를 읽어 Directory를 생성하고 파일을 저장한다.
        while ((entry = jis.getNextJarEntry()) != null) {
            String destFile = dest + entry.getName();
            if (entry.isDirectory()) {
                File a = new File(destFile);
                if (a.mkdir()) {
                    System.out.println(destFile + " 디렉토리 생성!!");
                    continue;
                } else {
                    System.out.println(destFile + " 디렉토리 생성실패!!");
                }
                continue;
            }
            System.out.println(destFile + " 파일 생성");
            fos = new FileOutputStream(dest + entry.getName());
            int BUFFER = 8196;
            byte data[] = new byte[BUFFER];
            int count;
            while ((count = jis.read(data, 0, BUFFER)) != -1) {
                fos.write(data, 0, count);
            }
            fos.close();
        }
        jis.close();
    }
}