1

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

4

1 回答 1

2

BufferedInputStreamGZIPInputStream, 为性能创建了您的,您将以相反的顺序执行此操作。另外,我建议您缩小缓冲区大小(并使用缓冲流)。最后,我会使用一个try-with-resources声明,它可能看起来像

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;
}
于 2015-01-23T05:51:44.430 回答