簡體   English   中英

在java中使用GZIP壓縮字節數組

[英]Compressing byte arrays using GZIP in java

我一直在研究使用 GZIP 壓縮字節數組並通過屬於套接字的 outputStream 發送它的函數。 它可以正常下載,但是當嘗試在我的 PC 上解壓縮時,它說該文件已損壞。

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

不知道什么崩潰。 有什么建議嗎?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM