Thursday 8 January 2015

Java : Decompress files from zip file


1. Read ZIP file with "ZipInputStream"
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFile));

2. Get the files to “ZipEntry” and output it to "FileOutputStream".
ZipEntry zipEntry = zipIn.getNextEntry();

Below Application provides functionalities to compress and decompress data.

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.

5.   public static void unZip(String zipFile, String outputFolder, int bufferSize)
6.   public static void unZip(String zipFile, String outputFolder)

Above two functions are used to decompress data.
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;
import java.util.zip.ZipInputStream;

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].getCanonicalPath()));
            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 static void unZip(String zipFile, String outputFolder, int bufferSize) {
        byte[] buffer = new byte[bufferSize];
        ZipInputStream zipIn = null;

        try {
            //create output directory is not exists
            File folder = new File(outputFolder);
            if (!folder.exists()) {
                folder.mkdir();
            }

            //get the zip file content
            zipIn = new ZipInputStream(new FileInputStream(zipFile));
            //get the zipped file list entry
            ZipEntry zipEntry = zipIn.getNextEntry();

            while (zipEntry != null) {
                String fileName = zipEntry.getName();
                File newFile = new File(outputFolder + File.separator + fileName);

                System.out.println("unzipping : " + newFile.getAbsoluteFile());

                //create all non exists folders, else you will hit FileNotFoundException for compressed folder
                new File(newFile.getParent()).mkdirs();

                FileOutputStream fos = new FileOutputStream(newFile);

                int len;
                while ((len = zipIn.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }

                fos.close();
                zipIn.closeEntry();
                zipEntry = zipIn.getNextEntry();
            }


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (zipIn != null) {
                try {
                    zipIn.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void unZip(String zipFile, String outputFolder) {
        unZip(zipFile, outputFolder, 1024);
    }
}

public class TestFileUtil {

    public static void main(String args[]) throws Exception {
        String zipFile = "E:\\Newfolder\\data.zip";
        String directory = "D:\\uncompressed";

        FileUtil.unZip(zipFile, directory);
    }
}


Sample Output
unzipping : D:\uncompressed\InitConfig.java
unzipping : D:\uncompressed\NewClass.java
unzipping : D:\uncompressed\sample.txt
unzipping : D:\uncompressed\TestFileUtil.java
unzipping : D:\uncompressed\New folder\FileUtil.java
unzipping : D:\uncompressed\New folder\InitConfig.java
unzipping : D:\uncompressed\FileUtil.java


Related Links

      Compress and archive files in zip format 
 
 

No comments:

Post a Comment