在Java中使用GZIP压缩字节数组

3

我一直在研究使用GZIP压缩字节数组并通过套接字的输出流发送它的函数。它可以正常下载,但是当我尝试在我的电脑上解压缩时,它说文件已损坏。

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();
    }

不知道是什么导致了崩溃。有什么建议吗?
1个回答

3
  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();  
  }  
 }  

你不应该没有解释就放弃编码。 - Andrewcpu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接