Добавьте папку с файлами в zip-файл, используя JAVA - PullRequest
1 голос
/ 02 февраля 2010

Я использую java java.util.zip api для добавления файлов и папок в zip-файл, но когда я добавляю несколько файлов в одну папку, он удаляет старое содержимое. Можно ли как-нибудь добавить файлы в zip-файл без изменения существующего содержимого в папке ?. Пожалуйста, помогите, это важно!

Это мой пример кода:

ZipOutputStream zip = null;
FileOutputStream fileWriter = null;
fileWriter = new FileOutputStream(destZipFile);
zip = new ZipOutputStream(fileWriter);
zip.putNextEntry(new ZipEntry(destFilePath));
zip.write(content);
zip.flush();
zip.close();

Ответы [ 2 ]

2 голосов
/ 02 февраля 2010

Если вы хотите добавить новый файл к существующему zip-файлу, вы должны сначала распаковать все, затем добавить все файлы и снова заархивировать.

См. эту ссылку для образцов.

1 голос
/ 02 февраля 2010

Я нашел это однажды ... Он создает временный файл и добавляет все файлы из существующего zip в «новый» zip перед добавлением дополнительных файлов. Если два файла имеют одинаковое имя, он добавляет только самый новый.

public static void addFilesToExistingZip(File zipFile,
         File[] files) throws IOException {
            // get a temp file
    File tempFile = File.createTempFile(zipFile.getName(), null);
            // delete it, otherwise you cannot rename your existing zip to it.
    tempFile.delete();

    boolean renameOk=zipFile.renameTo(tempFile);
    if (!renameOk)
    {
        throw new RuntimeException("could not rename the file "+zipFile.getAbsolutePath()+" to "+tempFile.getAbsolutePath());
    }
    byte[] buf = new byte[1024];

    ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));

    ZipEntry entry = zin.getNextEntry();
    while (entry != null) {
        String name = entry.getName();
        boolean notInFiles = true;
        for (File f : files) {
            if (f.getName().equals(name)) {
                notInFiles = false;
                break;
            }
        }
        if (notInFiles) {
            // Add ZIP entry to output stream.
            out.putNextEntry(new ZipEntry(name));
            // Transfer bytes from the ZIP file to the output file
            int len;
            while ((len = zin.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        }
        entry = zin.getNextEntry();
    }
    // Close the streams        
    zin.close();
    // Compress the files
    for (int i = 0; i < files.length; i++) {
        InputStream in = new FileInputStream(files[i]);
        // Add ZIP entry to output stream.
        out.putNextEntry(new ZipEntry(files[i].getName()));
        // 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();
    tempFile.delete();
}

EDIT: Я думаю, что этому больше 2 лет, так что, возможно, некоторые вещи не очень актуальны.

...