,
Share with your friends 

ZIP files in a folder using Java Program

8 ratings Views 109 
Author: GIFSTON (GIFSTON DANIEL.B I yr M.E CSE, Dr.Sivanthi Aditanar College of Engineering)  View Profile |  View other solutions by this author

Question / Problem


This Java sample program demonstrates two things. 1. Zip files. 2. To list all the files in a folder Most often, there is a need to zip files programmatically. In my case i had to automate the process of zipping and emailing the zipped file to the administrator at the end of every day

Solution

import java.io.*;
import java.util.zip.*;
public class Zip {
   static final int BUFFER = 2048;
   public static void main (String argv[]) {
      try {
         BufferedInputStream origin = null;
         FileOutputStream dest = new
           FileOutputStream("g:\\zip\\myfigs.zip");
         ZipOutputStream out = new ZipOutputStream(new
           BufferedOutputStream(dest));
         //out.setMethod(ZipOutputStream.DEFLATED);
         byte data[] = new byte[BUFFER];
         // get a list of files from current directory
         File f = new File(".");
         String files[] = f.list();

         for (int i=0; i<files.length; i++) {
            System.out.println("Adding: "+files[i]);
            FileInputStream fi = new
              FileInputStream(files[i]);
            origin = new
              BufferedInputStream(fi, BUFFER);
            ZipEntry entry = new ZipEntry(files[i]);
            out.putNextEntry(entry);
            int count;
            while((count = origin.read(data, 0,
              BUFFER)) != -1) {
               out.write(data, 0, count);
            }
            origin.close();
         }
         out.close();
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}


Applies to

Core Java

Rank It

Login to rank it

Report


Advertisement