Saturday, May 31, 2008

Create your own Zip Utility using Java

Hello frnds,
One more reference for me as well as for you also...
This is a program to create a zip file using Java.


import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import java.io.*;

/**
 *
 * @author Ravi
 */
public class Zip {
static Vector listFiles = new Vector();
String pathname = "";
public Zip() {
        try {
            File fZipped = new File("D:/a.zip");
            ZipOutputStream zout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(fZipped)));
            BufferedInputStream in = null;
            byte data[] = new byte[1000];
            String temp = "D:/ToDoList-CS";
            File ff = new File(temp);
            if (ff.isDirectory()) {
                pathname = ff.getAbsolutePath();
            } else {
                pathname =  ff.getParent();
            }
            System.out.println("Path is " + pathname);
            getList(temp); // stores a list of all files in a vector
            ZipEntry entry;
            for (int i = 0; i < listFiles.size(); i++) {
                entry = new ZipEntry(listFiles.get(i).toString());
                zout.putNextEntry(entry);
                System.out.println("Entry is " + entry.toString());
                File f = new File(listFiles.get(i).toString());
                if (f.isFile()) {
                    in = new BufferedInputStream(new FileInputStream(pathname + "/" + listFiles.get(i).toString()));
                    int count = 0;
                    while ((count = in.read(data, 0, 1000)) != -1) {
                        zout.write(data,0,count);
                    }
                }
                zout.flush();
                zout.closeEntry();
            }
            zout.flush();
            zout.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 public void getList(String path) {
        File toList = new File(path);
        File list[] = toList.listFiles();
        for (int i = 0; i < list.length; i++) {
            String temp = ((list[i].getAbsolutePath()).substring(pathname.length() + 1));
            String temp2 = "";
            for (int j = 0; j < temp.length(); j++) {
                char c = temp.charAt(j);
                if (c == '\\') {
                    c = '/';
                }
                temp2 += c;
            }
            if (list[i].isDirectory()) {
                temp2 += "/";
                listFiles.add(temp2);
            } else {
                listFiles.add(temp2);
            }
            if (list[i].isDirectory()) {
                getList(list[i].getAbsolutePath());
            }
        }
    }


    public static void main(String[] args) {
        new Zip();
    }
}

Note: Program is not optimized..
enjoy..

--
Ravi Kr. Gupta
http://techdc.blogspot.com

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.