GZIP compression to a byte array

后端 未结 6 1156
星月不相逢
星月不相逢 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:17

    To compress

    private static byte[] compress(byte[] uncompressedData) {
            ByteArrayOutputStream bos = null;
            GZIPOutputStream gzipOS = null;
            try {
                bos = new ByteArrayOutputStream(uncompressedData.length);
                gzipOS = new GZIPOutputStream(bos);
                gzipOS.write(uncompressedData);
                gzipOS.close();
                return bos.toByteArray();
    
            } catch (IOException e) {
                e.printStackTrace();
            }
            finally {
                try {
                    assert gzipOS != null;
                    gzipOS.close();
                    bos.close();
                }
                catch (Exception ignored) {
                }
            }
            return new byte[]{};
        }
    

    To uncompress

    private byte[] uncompress(byte[] compressedData) {
            ByteArrayInputStream bis = null;
            ByteArrayOutputStream bos = null;
            GZIPInputStream gzipIS = null;
    
            try {
                bis = new ByteArrayInputStream(compressedData);
                bos = new ByteArrayOutputStream();
                gzipIS = new GZIPInputStream(bis);
    
                byte[] buffer = new byte[1024];
                int len;
                while((len = gzipIS.read(buffer)) != -1){
                    bos.write(buffer, 0, len);
                }
                return bos.toByteArray();
            } catch (IOException e) {
                e.printStackTrace();
            }
            finally {
                try {
                    assert gzipIS != null;
                    gzipIS.close();
                    bos.close();
                    bis.close();
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return new byte[]{};
        }
    

提交回复
热议问题