Zlib compression Using Deflate and Inflate classes in Java

前端 未结 2 967
小鲜肉
小鲜肉 2020-12-08 17:03

I want trying to use the Deflate and Inflate classes in java.util.zip for zlib compression.

I am able to compress the code using Deflate, but while decompressing, I

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 17:48

    Paŭlo Ebermann's code can be further improved by using try-with-resources:

    import java.util.Scanner;
    import java.util.zip.*;
    import java.io.*;
    
    public class ZLibCompression
    {
        public static void compress(File raw, File compressed) throws IOException
        {
            try (InputStream inputStream = new FileInputStream(raw);
                 OutputStream outputStream = new DeflaterOutputStream(new FileOutputStream(compressed)))
            {
                copy(inputStream, outputStream);
            }
        }
    
        public static void decompress(File compressed, File raw)
                throws IOException
        {
            try (InputStream inputStream = new InflaterInputStream(new FileInputStream(compressed));
                 OutputStream outputStream = new FileOutputStream(raw))
            {
                copy(inputStream, outputStream);
            }
        }
    
        public static String decompress(File compressed) throws IOException
        {
            try (InputStream inputStream = new InflaterInputStream(new FileInputStream(compressed)))
            {
                return toString(inputStream);
            }
        }
    
        private static String toString(InputStream inputStream)
        {
            try (Scanner scanner = new Scanner(inputStream).useDelimiter("\\A"))
            {
                return scanner.hasNext() ? scanner.next() : "";
            }
        }
    
        private static void copy(InputStream inputStream, OutputStream outputStream)
                throws IOException
        {
            byte[] buffer = new byte[1000];
            int length;
    
            while ((length = inputStream.read(buffer)) > 0)
            {
                outputStream.write(buffer, 0, length);
            }
        }
    }
    

提交回复
热议问题