Как использовать Deflater и Inflater для больших файлов в Java? - PullRequest
0 голосов
/ 28 апреля 2018

Я хочу использовать Deflater и Inflater (НЕ DeflaterOutputStream и InflaterInputStream) для сжатия файлов. Проблема в том, что дефлятор перестает работать после того, как указанный размер буфера в этом случае равен 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");

    }
}

А это вывод (в windows) dir:

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 байта?

1 Ответ

0 голосов
/ 28 апреля 2018

finish() только для того, когда вы закончите. Это последнее, что вызывается после того, как вы предоставили все входные данные для объекта.

...