Edmond Tamas
Edmond Tamas

Reputation: 3285

java.util.zip.ZipOutputStream - Zipping large files faster?

I am wondering how could I speed up the zipping process of 40+ image files, in my android app.

Clients are sending images, which needs to be compressed or placed into a folder before uploading on the server. Now I use the bellow method, but this way files are zipped in about 20-30 seconds, while the phone appears to be frozen and users tend to exit the app :(

The method I use for zipping:

private static final int BUFFER_SIZE = 2048;

public void zip(String[] files, String zipFile) throws IOException {
        File zipDirectory = new File(Environment.getExternalStorageDirectory()
                + "/laborator/");
        if (!zipDirectory.exists()) {
            zipDirectory.mkdirs();
        } else {
            System.out.println("folder already exists!");
        }

        BufferedInputStream origin = null;
        ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
                new FileOutputStream(Environment.getExternalStorageDirectory()
                        + "/laborator/" + zipFile)));
        try {
            byte data[] = new byte[BUFFER_SIZE];

            for (int i = 0; i < files.length; i++) {
                FileInputStream fi = new FileInputStream(files[i]);
                origin = new BufferedInputStream(fi, BUFFER_SIZE);
                try {
                    ZipEntry entry = new ZipEntry(files[i].substring(files[i]
                            .lastIndexOf("/") + 1));
                    out.putNextEntry(entry);
                    int count;
                    while ((count = origin.read(data, 0, BUFFER_SIZE)) != -1) {
                        out.write(data, 0, count);
                    }
                } finally {
                    origin.close();
                }
            }
        } finally {
            out.close();
            System.out.println("ziping done");
            sendZip();
        }
    }

Upvotes: 2

Views: 3839

Answers (2)

Anthony
Anthony

Reputation: 1333

You could use

out.setLevel(Deflater.NO_COMPRESSION);

This way no need to change ZipEntry.

Upvotes: 1

wero
wero

Reputation: 32980

Since your images are jpgs chances are high that you don't get any decent compression within the ZIP file. So you could try to just put the images uncompressed into the ZIP file which should be considerable faster without increasing the size of the ZIP file:

ZipEntry entry = new ZipEntry(files[i].subs...
entry.setMethod(ZipEntry.STORED);
out.putNextEntry(entry);

Upvotes: 3

Related Questions