Zip more than 1 file

1

How can I zip more than one file? I'm only getting one. This is 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 a parameter in compactarParaZip method, what should I change? I can do Array of type File , so I think I could pass several files.

    
asked by anonymous 27.04.2015 / 18:22

1 answer

1

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

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();
}
    
27.04.2015 / 20:19