Poor Performance of Java's unzip utilities

后端 未结 3 2136
Happy的楠姐
Happy的楠姐 2021-02-09 02:07

I have noticed that the unzip facility in Java is extremely slow compared to using a native tool such as WinZip.

Is there a third party library available for Java that i

3条回答
  •  一向
    一向 (楼主)
    2021-02-09 02:46

    The problem is not the unzipping, it's the inefficient way you write the unzipped data back to disk. My benchmarks show that using

        InputStream is = zip.getInputStream(entry); // get the input stream
        OutputStream os = new java.io.FileOutputStream(f);
        byte[] buf = new byte[4096];
        int r;
        while ((r = is.read(buf)) != -1) {
          os.write(buf, 0, r);
        }
        os.close();
        is.close();
    

    instead reduces the method's execution time by a factor of 5 (from 5 to 1 second for a 6 MB zip file).

    The likely culprit is your use of bis.available(). Aside from being incorrect (available returns the number of bytes until a call to read would block, not until the end of the stream), this bypasses the buffering provided by BufferedInputStream, requiring a native system call for every byte copied into the output file.

    Note that wrapping in a BufferedStream is not necessary if you use the bulk read and write methods as I do above, and that the code to close the resources is not exception safe (if reading or writing fails for any reason, neither is nor os would be closed). Finally, if you have IOUtils in the class path, I recommend using their well tested IOUtils.copy instead of rolling your own.

提交回复
热议问题