package it.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipFile {
    private List<String> listaFiles;
    private String nomeZip;
       public ZipFile(List<String> listaFile,String nomeZip){
             this.nomeZip=nomeZip;
             this.listaFiles=listaFile;
       }
       public ZipFile(String nomeFile,String nomeZip){
             listaFiles=new LinkedList<String>();
             listaFiles.add(nomeFile);
             this.nomeZip=nomeZip;
       }
       public static void main(String[] args) {
             try
             {
                    ZipFile     zf=new ZipFile("out/AMF050_test_20100601_20110228.txt", "out/test.zip");
                    zf.zippa();
             }
             catch(Exception     ex){
                    ex.printStackTrace();
             }            
       }
       /**
        * Per evitare che dentro     lo zip sia ricreata <br>
        * la eventuale struttura     delle directory e sottodirectory del file di origine
        * @param nome
        * @return
        */
       private String     nomeFile(String nome){
             StringBuffer sb=new StringBuffer();
             if(nome.indexOf("/")>0){
                    sb.append(nome.substring(nome.lastIndexOf("/")+1));
             }
             else if(nome.indexOf(File.separator)>0){
                    sb.append(nome.substring(nome.lastIndexOf(File.separator)+1));
             }
             else
             {
                    sb.append(nome);
             }
             return sb.toString();
       }
       public void zippa() throws Exception
       {
             byte[] buf     = new byte[1024];
              ZipOutputStream out = new     ZipOutputStream(new FileOutputStream(nomeZip));
              for(String file:listaFiles){
                     FileInputStream in = new     FileInputStream(file);
                     out.putNextEntry(new     ZipEntry(nomeFile(file))); 
                     int len;
                     while ((len = in.read(buf))     > 0) {
                         out.write(buf, 0, len);
                     }
                     out.closeEntry();
                     in.close();
              }
              out.close();
       }
}
Nessun commento:
Posta un commento