aboutsummaryrefslogtreecommitdiff
path: root/src/XZSeekEncDemo.java
blob: 157e78825da300874be9d5e84c810e53895934bf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
 * XZSeekEncDemo
 *
 * Author: Lasse Collin <lasse.collin@tukaani.org>
 *
 * This file has been put into the public domain.
 * You can do whatever you want with this file.
 */

import java.io.*;
import org.tukaani.xz.*;

/**
 * Compresses a single file from standard input to standard ouput into
 * a random-accessible .xz file.
 * <p>
 * Arguments: [preset [block size]]
 * <p>
 * Preset is an LZMA2 preset level which is an integer in the range [0, 9].
 * The default is 6.
 * <p>
 * Block size specifies the amount of uncompressed data to store per
 * XZ Block. The default is 1 MiB (1048576 bytes). Bigger means better
 * compression ratio. Smaller means faster random access.
 */
class XZSeekEncDemo {
    public static void main(String[] args) throws Exception {
        LZMA2Options options = new LZMA2Options();

        if (args.length >= 1)
            options.setPreset(Integer.parseInt(args[0]));

        int blockSize = 1024 * 1024;
        if (args.length >= 2)
            blockSize = Integer.parseInt(args[1]);

        options.setDictSize(Math.min(options.getDictSize(),
                                     Math.max(LZMA2Options.DICT_SIZE_MIN,
                                              blockSize)));

        System.err.println("Encoder memory usage: "
                           + options.getEncoderMemoryUsage() + " KiB");
        System.err.println("Decoder memory usage: "
                           + options.getDecoderMemoryUsage() + " KiB");
        System.err.println("Block size:           " + blockSize + " B");

        XZOutputStream out = new XZOutputStream(System.out, options);

        byte[] buf = new byte[8192];
        int left = blockSize;

        while (true) {
            int size = System.in.read(buf, 0, Math.min(buf.length, left));
            if (size == -1)
                break;

            out.write(buf, 0, size);
            left -= size;

            if (left == 0) {
                out.endBlock();
                left = blockSize;
            }
        }

        out.finish();
    }
}