Thursday, 8 January 2015

Java : Compress and archive files in zip format


“java.util” package provides classes to compress files. Below is the step by step procedure to compress a directory.

Step 1: Create ZipOutputStream object.
FileOutputStream fout = new FileOutputStream(“temp.zip");
ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(fout));

Step 2: Open the directory that you want to compress.
File dir = new File(directory);

Step 3: Get list of files in given directory.
String files[] = dir.list();

Step 4: Read file one by one and create one ZipEntry for each file in the directory.
for (int i = 0; i < files.length; i++) {
    System.out.println("Adding: " + files[i]);
    FileInputStream fi = new FileInputStream(absolutePath + "\\" + files[i]);
    origin = new BufferedInputStream(fi, 1024);
    ZipEntry entry = new ZipEntry(files[i]);
    zipOut.putNextEntry(entry);
    int count;
    while ((count = origin.read(data, 0, 1024)) != -1) {
 zipOut.write(data, 0, count);
    }
    origin.close();
}


ZipEntry entry = new ZipEntry(files[i]))
Create a zip entry for each file that is read.

Below Application performs two types of compression.
1.   public static void zipOnlyFiles(String directory, String zipFIleName, int bufferSize)
2.   public static void zipOnlyFiles(String directory, String zipFIleName)

Above two functions used to compress files in a directory, but it won’t compress sub-directories.

3.   public static void zipAll(String dir, String zipFileName, int bufferSize)
4.   public static void zipAll(String dir, String zipFileName)

Above two functions used to compress directory, including sub-directories also.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
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 FileUtil {

    /**
     * takes directory path to compress and zipFileName to save compressed data
     * Method compress only files not directories
     */
    public static void zipOnlyFiles(String directory, String zipFIleName, int bufferSize) {
        FileOutputStream fout = null;
        ZipOutputStream zipOut = null;
        byte data[] = new byte[bufferSize];
        BufferedInputStream origin = null;

        try {
            fout = new FileOutputStream(zipFIleName + ".zip");
            zipOut = new ZipOutputStream(new BufferedOutputStream(fout));

            File dir = new File(directory);
            String absolutePath = dir.getAbsolutePath();

            String files[] = dir.list();

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

    /**
     * Method compress all files and sub directories
     * @param directoryr
     * @param zipFileName
     * @throws Exception
     */
    public static void zipAll(String directory, String zipFileName, int bufferSize){
        ZipOutputStream out = null;
        try{
            File dirObj = new File(directory);
            out = new ZipOutputStream(new FileOutputStream(zipFileName + ".zip"));
            addDir(dirObj, out, bufferSize);
        }
        catch(Exception e){
            
        }
        finally{
            if(out != null){
                try {
                    out.close();
                } catch (IOException ex) {
            
                }
            }
        }
       
    }

    static private void addDir(File dirObj, ZipOutputStream out, int bufferSize) throws IOException {
        File[] files = dirObj.listFiles();
        byte[] tmpBuf = new byte[bufferSize];

        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                addDir(files[i], out, bufferSize);
                continue;
            }
            FileInputStream in = new FileInputStream(files[i].getAbsolutePath());
            BufferedInputStream origin = new BufferedInputStream(in, bufferSize);
            System.out.println(" Adding: " + files[i].getAbsolutePath());
            out.putNextEntry(new ZipEntry(files[i].getAbsolutePath()));
            int len;
            while ((len = origin.read(tmpBuf)) > 0) {
                out.write(tmpBuf, 0, len);
            }
            out.closeEntry();
            origin.close();
        }
    }

     public static void zipAll(String directory, String zipFileName){
         zipAll(directory,zipFileName,1024);
     }

     public static void zipOnlyFiles(String directory, String zipFIleName){
         zipOnlyFiles(directory, zipFIleName, 1024);
     }
}

public class TestFileUtil {
    public static void main(String args[]) throws Exception {
        String directory = "E:\\Newfolder";
        String zipFileName = "temp";
        FileUtil.zipAll(directory, zipFileName, 5000);
    }
}


Sample Output
 Adding: E:\Newfolder\1.sql
 Adding: E:\Newfolder\2.sql
 Adding: E:\Newfolder\3.sql
 Adding: E:\Newfolder\4.sql
 Adding: E:\Newfolder\5.sql
 Adding: E:\Newfolder\abc\InitConfig.java


Related Links

      Decompress files from zip file

No comments:

Post a Comment