Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 332
  • Last Modified:

Java code to zip the any formatted files and copy them to a local directory

  I have got a list of .pdf or any formatted files that will be placed in a directory.  I need a java program to look for this directory, get the files, zip them into a single zip and copy it to a local directory.


ZIp them all to files.zip and copy them to D:\

1 Solution
What problem are you having with this exactly?

(1) Traverse through each directory within the root drive, and check each directory for the files.
(2) If file is found, copy it to a temp folder.
(3) Once all folders have been searched, turn the temp folder into a ZIP (example: http://javaalmanac.com/egs/java.util.zip/CreateZip.html)

Try each stage, one by one, and let us know which one you're having trouble with.
I for one am pretty reluctant to just code the solution for you.

[We're here to help you learn, not to provide solutions that you could pay for on rentacoder.com..]

Give the Folder name to be zipped in the Path Variable, it will convert  all the files in that folder to a zip file.

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 CreateZIP {

      public static void main(String[] args){

          String[] filenames=null;
          String path = "E:\\jack\\";
          File dir = new File(path);
                filenames = dir.list();
                System.out.println("Not a Directory");
          byte[] buf = new byte[1024];
          try {
              String outFilename = path+"outfile.zip";
              ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));
              for (int i=0; i<filenames.length; i++) {
                    filenames[i]= path+filenames[i];
                  FileInputStream in = new FileInputStream(filenames[i]);
                  out.putNextEntry(new ZipEntry(filenames[i]));
                  int len;
                  while ((len = in.read(buf)) > 0) {
                      out.write(buf, 0, len);
          } catch (IOException e) {

mukundhansureshAuthor Commented:
Thanks. It works perfect

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now