GZIP compression to a byte array

后端 未结 6 1157
星月不相逢
星月不相逢 2020-12-13 21:00

I am trying to write a class that can compress data. The below code fails (no exception is thrown, but the target .gz file is empty.)
Besides: I don\'t want to generate

6条回答
  •  生来不讨喜
    2020-12-13 21:10

    I've improved JITHINRAJ's code - used try-with-resources:

    private static byte[] gzipCompress(byte[] uncompressedData) {
            byte[] result = new byte[]{};
            try (ByteArrayOutputStream bos = new ByteArrayOutputStream(uncompressedData.length);
                 GZIPOutputStream gzipOS = new GZIPOutputStream(bos)) {
                gzipOS.write(uncompressedData);
                // You need to close it before using bos
                gzipOS.close();
                result = bos.toByteArray();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }
    
    private static byte[] gzipUncompress(byte[] compressedData) {
            byte[] result = new byte[]{};
            try (ByteArrayInputStream bis = new ByteArrayInputStream(compressedData);
                 ByteArrayOutputStream bos = new ByteArrayOutputStream();
                 GZIPInputStream gzipIS = new GZIPInputStream(bis)) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = gzipIS.read(buffer)) != -1) {
                    bos.write(buffer, 0, len);
                }
                result = bos.toByteArray();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }
    

提交回复
热议问题