How to Zip files in JAVA : Complete Code Tested OK

String multiplezips = "c:\\tobo\\textfile1.txt,c:\\tobo\\textfile2.txt";
String zipFile = "c:\\tobo\\";
String[] srcFiles = multiplezips.split(",");
      try {
          // create byte buffer
          byte[] buffer = new byte[4096];
          FileOutputStream fos = new FileOutputStream(zipFile);
          ZipOutputStream zos = new ZipOutputStream(fos);
          for (int i=0; i < srcFiles.length; i++) {
              File srcFile = new File(srcFiles[i]);
              FileInputStream fis = new FileInputStream(srcFile);
              // begin writing a new ZIP entry, positions the stream to the start of the entry data
              zos.putNextEntry(new ZipEntry(srcFile.getName()));
              int length;
              while ((length = > 0) {
                  zos.write(buffer, 0, length);
              // close the InputStream
          // close the ZipOutputStream
      catch (Exception ioe) {
          System.out.println("Error creating zip file: " + ioe);

Above code illustrates conversion of few files into a zipped file.


multiplezips – This variable contains the files to be zipped in a comma seperated string.

zipFile – This is a string containing the name of the final file to be formed after compressiong all the child files from the variable multiplezips.

The above code is tested and working. Copy, paste and run.


For any queries do post in comments please.

4 thoughts on “How to Zip files in JAVA : Complete Code Tested OK

  1. Hmm it appears like your site ate my first comment (it was extremely
    long) so I guess I’ll just sum it up what I wrote and say, I’m thoroughly enjoying your blog.
    I too am an aspiring blog blogger but I’m still new to the whole
    thing. Do you have any tips and hints for inexperienced blog writers?
    I’d definitely appreciate it.

  2. Hi everyone, it’s my first pay a quick visit at this website, and piece of writing is genuinely fruitful in support of me, keep up
    posting such posts.

  3. Howdy just wanted to give you a quick heads up. The words in your
    content seem to be running off the screen in Ie. I’m not sure if this is a formatting issue or something to do with browser compatibility but I figured I’d post to let you know.
    The design and style look great though! Hope you get the problem resolved soon.

Leave a Reply

Your email address will not be published.

Verified by MonsterInsights