1 Reply Latest reply: Jan 24, 2008 5:53 AM by 800322 RSS

    How to zip files and folders in a directory into a zip file?

    807601
      I have written a zip code which can zip files from a directory into 1 zip file. However, when it encounters a folder in that directory, it compresses the folder into a seperate zip file.

      Below is the code:
        
      public void PerformZip(String startPath,String destZipFile)
      {
         try
         {
           int i;
      
           File startDir = new File(startPath);
            File[] fileArray = startDir.listFiles();
            FileOutputStream fileOutStream = new FileOutputStream(destZipFile);
            ZipOutputStream zipOS = new ZipOutputStream(fileOutStream);
      
           for(i = 0;i < fileArray.length;i++)
           {
               if(fileArray.isFile())
      {
      long size; int len;
      size = fileArray[i].length();
      System.out.println(size);
      byte[] buf = new byte[(int)size];

      FileInputStream fileInStream = new FileInputStream(fileArray[i].getPath());
      zipOS.setLevel(Deflater.BEST_COMPRESSION);
      zipOS.putNextEntry(new ZipEntry(fileArray[i].getName()));

      while(-1 !=(len=fileInStream.read(buf)))
      {
      System.out.println(len);
      zipOS.write(buf,0,len);
      }

      zipOS.closeEntry();
      fileInStream.close();
      }
      else if(fileArray[i].isDirectory())
      {
      String name = fileArray[i].getName();
      String start = fileArray[i].getPath();

      PerformZip(start,destZipFile);
      }
      }

      zipOS.close();

      }catch(IOException e)
      {
      System.out.println("Error zipping file");
      }


      }
      The part where the folder is dealt with is under the "elseif fileArray.isDirectory()) ". Recursion is used to get into the folder to read the files inside for compression.

      I have made the file and zip output streams to have the same location (destZipFile) so that the folder to be compressed can be placed in the same zip file. However, when I ran the program, there is no trace of the folder being zipped.

      How do I manage to zip all files and folders inside a directory into 1 zip file?