/*
 * Created on 2004/11/05
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.jware.util.crypt;

import java.io.*;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author jrmt
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class Zip implements Serializable
{
    static final int BUFFER_SIZE = 2048;
    
    /**
     * 
     */
    public Zip() {
        super();
    }

    private static void renameto(String src, String dest)
    {
        File sf = new File(src);
        File df = new File(dest);
        sf.renameTo(df);
    }

    private static void addFileToZip(ZipOutputStream out, File f)
        throws Exception
    {
        byte data[] = new byte[BUFFER_SIZE];
        BufferedInputStream origin = null;
        FileInputStream fis = new FileInputStream(f);
        origin = new BufferedInputStream(fis, 2048);
        ZipEntry entry = new ZipEntry(f.getName());
        out.putNextEntry(entry);
        int count;
        while((count = origin.read(data, 0, 2048)) != -1) 
            out.write(data, 0, count);
        origin.close();
    }

    public static boolean ZipFile(String destfn, ArrayList objs)
    {
        if(objs.size() == 0)
            return false;
        renameto(destfn, destfn + ".tmp");
        try
        {
            FileOutputStream dest = new FileOutputStream(destfn + ".tmp");
            ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
            for(int i = 0; i < objs.size(); i++)
            {
                String fn = (String)objs.get(i);
                File f = new File(fn);
                addFileToZip(out, f);
            }

            out.close();
            renameto(destfn + ".tmp", destfn);
        }
        catch(Exception e)
        {
            return false;
        }
        return true;
    }

}
