Zip more than 1 file

Asked

Viewed 821 times

1

How can I zip more than one file? I’m only getting one. That’s my code:

public static void compactarParaZip(String arqSaida, String arqEntrada)
        throws IOException {
    int cont;
    byte[] dados = new byte[TAMANHO_BUFFER];

    BufferedInputStream origem = null;
    FileInputStream streamDeEntrada = null;
    FileOutputStream destino = null;
    ZipOutputStream saida = null;
    ZipEntry entry = null;

    try {
        destino = new FileOutputStream(new File(arqSaida));
        saida = new ZipOutputStream(new BufferedOutputStream(destino));
        File file = new File(arqEntrada);
        streamDeEntrada = new FileInputStream(file);
        origem = new BufferedInputStream(streamDeEntrada, TAMANHO_BUFFER);
        entry = new ZipEntry(file.getName());
        saida.putNextEntry(entry);

        while ((cont = origem.read(dados, 0, TAMANHO_BUFFER)) != -1) {
            saida.write(dados, 0, cont);
        }
        origem.close();
        saida.close();
    } catch (IOException e) {
        throw new IOException(e.getMessage());
    }
}
}

If I pass 2 more files as parameter in the method compactarParaZip, what should I change? I have how to make a Array of the kind File, so I think I could pass several files.

  • You want the result to be only a compact file with all these passed by parameter or each one to be compressed separately?

  • 3

    http://stackoverflow.com/a/16547340/4056678

  • I want 1 file with all others passed by parameter.

1 answer

1


To avoid "breaking" the signature of compactarParaZip, you can change the subscription to a varargs, something like that:

public static void compactarParaZip(final String arqSaida, final String... arqEntradas) throws IOException { }

Hence, the implementation could be changed to something like this:

public static void compactarParaZip(final String arqSaida, final String... arqEntradas) throws IOException {
    int cont;
    final byte[] dados = new byte[TAMANHO_BUFFER];

    final FileOutputStream destino = new FileOutputStream(new File(arqSaida));
    final ZipOutputStream saida = new ZipOutputStream(new BufferedOutputStream(destino));

    for (final String arqEntrada : arqEntradas) {
        final File file = new File(arqEntrada);
        final FileInputStream streamDeEntrada = new FileInputStream(file);
        final BufferedInputStream origem = new BufferedInputStream(streamDeEntrada, TAMANHO_BUFFER);
        final ZipEntry entry = new ZipEntry(file.getName());
        saida.putNextEntry(entry);

        while ((cont = origem.read(dados, 0, TAMANHO_BUFFER)) != -1) {
            saida.write(dados, 0, cont);
        }
        origem.close();
    }

    saida.close();
}
  • Thank you very much, I got.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.