在 Java 中优化解压缩过程?

Optimizing Ungunzipping process in Java?

我对使用以下代码解压缩 .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,但 运行 仍然需要我几十分钟,所以我正在尝试更快地获取一些东西。速度不错:)

您从 GZIPInputStream 创建了 BufferedInputStream,为了提高性能,您将按相反的顺序进行操作。另外,我建议您缩小缓冲区大小(并使用缓冲流)。最后,我会使用 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;
}