unzip File to target dir - Android File Input Output

Android examples for File Input Output:Zip File

Description

unzip File to target dir

Demo Code


//package com.java2s;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class Main {
    private static final int BUFFER_SIZE = 1024 * 2;

    public static boolean unzip(File zipFile, File targetDir) {
        FileInputStream fis = null;
        ZipInputStream zis = null;
        ZipEntry zentry = null;//from www. j  a  v  a 2s .c o m

        try {
            try {

                fis = new FileInputStream(zipFile);
                zis = new ZipInputStream(fis);

                while ((zentry = zis.getNextEntry()) != null) {
                    String fileNameToUnzip = zentry.getName();

                    File targetFile = new File(targetDir, fileNameToUnzip);

                    if (zentry.isDirectory()) {//if is Directory
                        File path = new File(targetFile.getAbsolutePath());
                        if (!path.isDirectory()) {
                            path.mkdirs();
                        }
                    } else { //if is File 
                        File path = new File(targetFile.getParent());
                        if (!path.isDirectory()) {
                            path.mkdirs();
                        }
                        unzipEntry(zis, targetFile);
                    }
                }
            } finally {
                if (zis != null) {
                    zis.close();
                }
                if (fis != null) {
                    fis.close();
                }
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public static File unzipEntry(ZipInputStream zis, File targetFile)
            throws Exception {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(targetFile);

            byte[] buffer = new byte[BUFFER_SIZE];
            int len = 0;
            while ((len = zis.read(buffer)) != -1) {
                if (len == 0) {
                    return null;
                }
                fos.write(buffer, 0, len);
            }
        } finally {
            if (fos != null) {
                fos.close();
            }
        }
        return targetFile;
    }
}

Related Tutorials