Как мне создать ZIP-файл на Java? - PullRequest
8 голосов
/ 05 июня 2010

Что такое Java эквивалент этой команды jar:

C:\>jar cvf myjar.jar directory

Я бы хотел создать этот jar-файл программно, поскольку не уверен, что команда jar будет находиться в системном пути, где я мог бы просто запустить внешний процесс.

Редактировать : Все, что я хочу, это заархивировать (и сжать) каталог. Не должен следовать никаким стандартам Java. То есть: стандартный почтовый индекс в порядке.

Ответы [ 2 ]

12 голосов
/ 05 июня 2010
// These are the files to include in the ZIP file
    String[] source = new String[]{"source1", "source2"};

    // Create a buffer for reading the files
    byte[] buf = new byte[1024];

    try {
        // Create the ZIP file
        String target = "target.zip";
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(target));

        // Compress the files
        for (int i=0; i<source.length; i++) {
            FileInputStream in = new FileInputStream(source[i]);

            // Add ZIP entry to output stream.
            out.putNextEntry(new ZipEntry(source[i]));

            // Transfer bytes from the file to the ZIP file
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }

            // Complete the entry
            out.closeEntry();
            in.close();
        }

        // Complete the ZIP file
        out.close();
    } catch (IOException e) {
    }

Вы также можете использовать ответ из этого поста Как использовать JarOutputStream для создания файла JAR?

4 голосов
/ 05 июня 2010

Все, что вам нужно, находится в пакете java.util.jar:

http://java.sun.com/javase/6/docs/api/java/util/jar/package-summary.html

...