package com.rjconsultores.ventaboletos.web.utilerias;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class CompactarParaZip {

	private List<File> arquivosACompactar;
	private String caminhoArquivoDeSaida;
	final byte[] buffer;
	
	public CompactarParaZip(List<File> arquivosACompactar, String caminhoArquivoDeSaida) {
		this.arquivosACompactar = arquivosACompactar;
		this.caminhoArquivoDeSaida = caminhoArquivoDeSaida;
		buffer = new byte[1024];
	}
	
	public void compactar() throws IOException {
		ZipOutputStream out = new ZipOutputStream(new FileOutputStream(caminhoArquivoDeSaida));
		try {
			for (File fileZip : arquivosACompactar) {
				escreverSaida(out, fileZip);
			}
		} finally {
			out.close();
		}
	}

	private void escreverSaida(final ZipOutputStream out, final File fileZip) throws IOException {
		FileInputStream in = new FileInputStream(fileZip.getPath());
		int len;
		try {
			out.putNextEntry(new ZipEntry(fileZip.getName()));
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
		} finally {
			out.closeEntry();
			in.close();
		}
	}
}
