【问题标题】:How to use Deflater and Inflater on large files in java?如何在 java 中的大文件上使用 Deflater 和 Inflater?
【发布时间】:2018-10-09 05:24:01
【问题描述】:

我想使用DeflaterInflater(不是DeflaterOutputStreamInflaterInputStream)来压缩文件。问题是在本例中提到的缓冲区大小为 1024 后,放气器停止工作。我正在使用以下代码:

public class CompressionUtils {

    static String deflateInput = "pic.jpg";
    static String deflateOutput = "picDeflate.raw";
    static String inflateOutput = "picInflate.jpg";

    public static void compress() throws IOException {
        Deflater deflater = new Deflater();
        byte[] data = new byte[1024];
        FileInputStream in = new FileInputStream(new File(deflateInput));
        FileOutputStream out = new FileOutputStream(new File(deflateOutput));

        long readBytes = 0;
        while ((readBytes = in.read(data, 0, 1024)) != -1) {
            deflater.setInput(data);
            deflater.finish();
            byte[] buffer = new byte[1024];
            while (!deflater.finished()) {
                int count = deflater.deflate(buffer); // returns the generated code... index  
                out.write(buffer, 0, count);
            }
        }
    }

    public static void decompress() throws IOException, DataFormatException {
        Inflater inflater = new Inflater();
        byte[] data = new byte[1024];
        FileInputStream in = new FileInputStream(new File(deflateOutput));
        FileOutputStream out = new FileOutputStream(new File(inflateOutput));
        long readBytesCount = 0;
        long readCompressedBytesCount = 0;
        long readBytes = 0;
        while ((readBytes = in.read(data, 0, 1024)) != -1) {
            readBytesCount = readBytesCount + readBytes;
            inflater.setInput(data);
            byte[] buffer = new byte[1024];
            while (!inflater.finished()) {
                int count = inflater.inflate(buffer);
                System.out.println("Remaining: " + inflater.getRemaining());
                out.write(buffer, 0, count);
            }
        }
        System.out.println("readBytesCount: " + readBytesCount);
    }

    public static void main(String[] args) {
        System.out.println("Operation started");
        try {
            compress();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Operation ended");

    }
}

这是dir的输出(在windows中):

01-04-2018  16:52           220,173 pic.jpg
28-04-2018  20:50               943 picDeflate.raw
28-04-2018  20:28             1,024 picInflate.jpg

为什么压缩代码在读取 1024 字节后停止?

【问题讨论】:

    标签: java deflate inflate lossless-compression


    【解决方案1】:

    finish() 仅在您完成时使用。它是您向对象提供所有输入数据后调用的最后一件事。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-22
      • 1970-01-01
      相关资源
      最近更新 更多