Tuesday 12 November 2013

search files and zip them

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

public class MultiZip2 {
   
     public static void main(String[] args) {
       
       //plz give ur source folder path(root folder)
         String sourcepath = "/root/Desktop/mohammad shadab/zipdata";
        findFile(sourcepath); 
    }
   
   
   
   
    public static void zipAndStore(String currentPath)
    {
        System.out.println(currentPath);
        File fname=new File(currentPath);
        String name=fname.getName();
        String entryName=null;
        //plz replace the "/root/Desktop/myzip/" by ur destination folder from following line.
        String destinationPath="/root/Desktop/myzip/"+name+".zip";
         entryName =name;
        System.out.println(name);
       
           byte[] buffer = new byte[1024];
          
            try{

                FileOutputStream fos = new FileOutputStream(destinationPath);
                ZipOutputStream zos = new ZipOutputStream(fos);
                ZipEntry ze= new ZipEntry(entryName);
                zos.putNextEntry(ze);
                FileInputStream in = new FileInputStream(new File(currentPath));

                int len;
                while ((len = in.read(buffer)) > 0) {
                    zos.write(buffer, 0, len);
                }

                in.close();
                zos.closeEntry();

               
                zos.close();


            }catch(IOException ex){
               ex.printStackTrace();
            }
             

       
    }
    public static void findFile(String path)
    {
        File folder = new File(path);
          File[] listOfFiles = folder.listFiles();
          for (int i = 0; i < listOfFiles.length; i++)
          {
              if(listOfFiles[i].isDirectory())
              {
                  findFile(listOfFiles[i].getAbsolutePath());
              }
              else{
                  zipAndStore(listOfFiles[i].getAbsolutePath());
                 
              }
          }
    }

}