简体   繁体   中英

Compressing byte arrays using GZIP in java

I've been working on a function that compresses an array of bytes using GZIP and sends it through an outputStream that belongs to a socket. It downloads fine but when trying to decompress on my PC it says that file is corrupted.

private void Zip(byte[] datatocompress)
    {
            ZipOutputStream zippoutstream = new ZipOutputStream(outputstream);

            zippoutstream.putNextEntry(new ZipEntry("file.html"));
            zippoutstream.write(datatocompress);
            zippoutstream.closeEntry();
            zippoutstream.flush();
            zippoutstream.close();
    }

No idea about what crashes. Any suggestion?

  public static byte[] gzip(byte[] val) throws IOException {  
  ByteArrayOutputStream bos = new ByteArrayOutputStream(val.length);  
  GZIPOutputStream gos = null;  
  try {  
   gos = new GZIPOutputStream(bos);  
   gos.write(val, 0, val.length);  
   gos.finish();  
   gos.flush();  
   bos.flush();  
   val = bos.toByteArray();  
  } finally {  
   if (gos != null)  
    gos.close();  
   if (bos != null)  
    bos.close();  
  }  
  return val;  
 }  

 /** 
  * Compress
  *  
  * @param source 
  *
  * @param target 
  *           
  * @throws IOException 
  */  
 public static void zipFile(String source, String target) throws IOException {  
  FileInputStream fin = null;  
  FileOutputStream fout = null;  
  GZIPOutputStream gzout = null;  
  try {  
   fin = new FileInputStream(source);  
   fout = new FileOutputStream(target);  
   gzout = new GZIPOutputStream(fout);  
   byte[] buf = new byte[1024];  
   int num;  
   while ((num = fin.read(buf)) != -1) {  
    gzout.write(buf, 0, num);  
   }  
  } finally {  
   if (gzout != null)  
    gzout.close();  
   if (fout != null)  
    fout.close();  
   if (fin != null)  
    fin.close();  
  }  
 }  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM