Tuesday, May 3, 2016

Android Fast Unzip Programatically


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import android.util.Log;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * @credit http://stackoverflow.com/a/21159437/1730484
 */
public class Decompress {
    private String _zipFile;
    private String _location;

    public interface DecompressListener {
        public void onFinish(String zipfile);
    }

    public Decompress(String zipFile, String location) {
        _zipFile = zipFile;
        _location = location;

        hanldeDirectory("");
    }

    public void unzip(DecompressListener listener) {

        try {
            FileInputStream inputStream = new FileInputStream(_zipFile);
            ZipInputStream zipStream = new ZipInputStream(inputStream);
            ZipEntry zEntry = null;
            while ((zEntry = zipStream.getNextEntry()) != null) {
                Log.d("Unzip", "Unzipping " + zEntry.getName() + " at "
                        + _location);

                if (zEntry.isDirectory()) {
                    hanldeDirectory(zEntry.getName());
                } else {
                    FileOutputStream fout = new FileOutputStream(
                            this._location + "/" + zEntry.getName());
                    BufferedOutputStream bufout = new BufferedOutputStream(fout);
                    byte[] buffer = new byte[1024];
                    int read = 0;
                    while ((read = zipStream.read(buffer)) != -1) {
                        bufout.write(buffer, 0, read);
                    }

                    zipStream.closeEntry();
                    bufout.close();
                    fout.close();
                }
            }
            zipStream.close();
            Log.d("Unzip", "Unzipping complete. path :  " + _location);
        } catch (Exception e) {
            Log.d("Unzip", "Unzipping failed");
            e.printStackTrace();
        } finally {
            if (listener != null)
                listener.onFinish(_zipFile);
        }

    }

    public void hanldeDirectory(String dir) {
        File f = new File(this._location + dir);
        if (!f.isDirectory()) {
            f.mkdirs();
        }
    }
}

No comments:

Post a Comment