在Java中优化Ungunzipping进程?

时间:2015-01-23 05:39:46

标签: java performance optimization compression gunzip

我在使用以下代码解压缩.gz文件所需的时间有问题:

import java.io.*;
import java.util.zip.*;

public class UnGunzipClass{

    public static boolean ungunzip(String compressedFile, String decompressedFile){

        try{

            // in
            FileInputStream fileIn          = new FileInputStream(compressedFile);
            GZIPInputStream gZipIn          = new GZIPInputStream(fileIn);
            BufferedInputStream in          = new BufferedInputStream(gZipIn);

            // out
            FileOutputStream fileOut        = new FileOutputStream(decompressedFile);
            BufferedOutputStream out        = new BufferedOutputStream(fileOut);

            int n = 0;
            int len = 1024*1024*1024;
            byte[] buffer = new byte[len];

            while((n = in.read(buffer,0,len)) > 0){
                out.write(buffer,0,n);
            }

            gZipIn.close();
            fileOut.close();

            return true;

        } catch (IOException e){
            e.printStackTrace();
            return false;
        }
    }
}

注意:文件高达100MB,但它仍然需要几十分钟的时间才能运行,所以我想要更快地获取更多内容。速度很快:)

1 个答案:

答案 0 :(得分:2)

您是从BufferedInputStream创建的GZIPInputStream,因为您会以相反的顺序执行此操作。另外,我建议你缩小缓冲区大小(并使用缓冲流)。最后,我会使用try-with-resources Statement,看起来像

public static boolean ungunzip(String compressedFile,
        String decompressedFile) {
    final int BUFFER_SIZE = 32768;
    try (InputStream in = new GZIPInputStream(new BufferedInputStream(
            new FileInputStream(compressedFile)), BUFFER_SIZE);
            OutputStream out = new BufferedOutputStream(
                    new FileOutputStream(decompressedFile), BUFFER_SIZE)) {
        int n = 0;
        byte[] buffer = new byte[BUFFER_SIZE];
        while ((n = in.read(buffer, 0, BUFFER_SIZE)) > 0) {
            out.write(buffer, 0, n);
        }
        return true;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}