How to use LZMA SDK to compress/decompress in Java

后端 未结 6 1084
灰色年华
灰色年华 2020-12-04 17:03

http://www.7-zip.org/sdk.html This site provide a LZMA SDK for compress/decompress files, I would like to give it a shot but I am lost.

Anyone got experience on this

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-04 17:28

    You can use this library instead. It is "outdated" but still works fine.

    Maven dependency

    
        com.github.jponge
        lzma-java
        1.2
    
    

    Utility class

    import lzma.sdk.lzma.Decoder;
    import lzma.streams.LzmaInputStream;
    import lzma.streams.LzmaOutputStream;
    import org.apache.commons.compress.utils.IOUtils;
    
    import java.io.*;
    import java.nio.file.Path;
    
    public class LzmaCompressor
    {
        private Path rawFilePath;
        private Path compressedFilePath;
    
        public LzmaCompressor(Path rawFilePath, Path compressedFilePath)
        {
            this.rawFilePath = rawFilePath;
            this.compressedFilePath = compressedFilePath;
        }
    
        public void compress() throws IOException
        {
            try (LzmaOutputStream outputStream = new LzmaOutputStream.Builder(
                    new BufferedOutputStream(new FileOutputStream(compressedFilePath.toFile())))
                    .useMaximalDictionarySize()
                    .useMaximalFastBytes()
                    .build();
                 InputStream inputStream = new BufferedInputStream(new FileInputStream(rawFilePath.toFile())))
            {
                IOUtils.copy(inputStream, outputStream);
            }
        }
    
        public void decompress() throws IOException
        {
            try (LzmaInputStream inputStream = new LzmaInputStream(
                    new BufferedInputStream(new FileInputStream(compressedFilePath.toFile())),
                    new Decoder());
                 OutputStream outputStream = new BufferedOutputStream(
                         new FileOutputStream(rawFilePath.toFile())))
            {
                IOUtils.copy(inputStream, outputStream);
            }
        }
    }
    

    Firstly you have to create a file with content to start compressing. You can use this website to generate random text.

    Example compression and decompression

    Path rawFile = Paths.get("raw.txt");
    Path compressedFile = Paths.get("compressed.lzma");
    
    LzmaCompressor lzmaCompressor = new LzmaCompressor(rawFile, compressedFile);
    lzmaCompressor.compress();
    lzmaCompressor.decompress();
    

提交回复
热议问题