views:

28

answers:

1

Hi there, my app downloads a zip with about 350 files. A mix of JPG and HTML files. The function i wrote to do it works just fine but the unzipping takes for ever. At first i thought the reason might be that writing to the sd-card is slow. but when i unzip the same zip with an other app on my phone it works much faster. is there anything that i could do to optimize it?

here is the code:

private void extract() {

    try {
        FileInputStream inStream = new FileInputStream(targetFilePath);
        ZipInputStream zipStream = new ZipInputStream(new BufferedInputStream(inStream));
        ZipEntry entry;
        ZipFile zip = new ZipFile(targetFilePath);

                    //i know the contents for the zip so i create the dirs i need in advance
        new File(targetFolder).mkdirs();
        new File(targetFolder + "META-INF").mkdir();
        new File(targetFolder + "content").mkdir();

        int extracted = 0;

        while((entry = zipStream.getNextEntry()) != null) {
            if (entry.isDirectory()) {
                new File(targetFolder + entry.getName()).mkdirs();
            } else {
                FileOutputStream outStream = new FileOutputStream(targetFolder + entry.getName());
                for (int c = zipStream.read(); c != -1; c = zipStream.read()) {
                    outStream.write(c);
                }
                zipStream.closeEntry();
                outStream.close();

                extracted ++;
            }

            publishProgress(""+(int)extracted*100/zip.size());
        }

        zipStream.close();
        inStream.close();
        //
        new File(targetFilePath).delete();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

thanks to CommonsWare i modified my code like this:

                    int size;
                byte[] buffer = new byte[2048];

                FileOutputStream outStream = new FileOutputStream(targetFolder + entry.getName());
                BufferedOutputStream bufferOut = new BufferedOutputStream(outStream, buffer.length);

                while((size = zipStream.read(buffer, 0, buffer.length)) != -1) {
                    bufferOut.write(buffer, 0, size);
                }

                bufferOut.flush();
                bufferOut.close();

big performance difference. Thanks a lot.

A: 

You are reading and writing a byte at a time. Consider reading and writing a larger block at a time.

CommonsWare
THANKS! That actually did the Trick.
par