2012-02-10 63 views
0

我有一个应用程序,其中服务A将向服务B提供压缩数据。服务B需要将其解压缩。解压缩文件的内容

服务A有一个公开方法getStream,它将ByteArrayInputStream作为输出,数据init是压缩数据。

但是,将该值传递给GzipInputStream会导致Gzip格式异常。

InputStream ins = method.getInputStream(); 
GZIPInputStream gis = new GZIPInputStream(ins); 

这给出了一个例外。当文件被转储到服务A时,数据被压缩。所以getInputStream给出了压缩数据。

如何处理它并将其传递给GzipInputStream?

问候
Dheeraj乔希

回答

1

如果拉上,则必须使用ZipInputstream

1

它取决于“zip”格式。有多种格式具有zip名称(zip,gzip,bzip2,lzip),不同的格式需要不同的解析器。
http://en.wikipedia.org/wiki/List_of_archive_formats
http://www.codeguru.com/java/tij/tij0115.shtml
http://docstore.mik.ua/orelly/java-ent/jnut/ch25_01.htm

如果您使用的拉链那就试试这个代码:

public void doUnzip(InputStream is, String destinationDirectory) throws IOException { 
    int BUFFER = 2048; 

    // make destination folder 
    File unzipDestinationDirectory = new File(destinationDirectory); 
    unzipDestinationDirectory.mkdir(); 

    ZipInputStream zis = new ZipInputStream(is); 

    // Process each entry 
    for (ZipEntry entry = zis.getNextEntry(); entry != null; entry = zis 
      .getNextEntry()) { 

     File destFile = new File(unzipDestinationDirectory, entry.getName()); 

     // create the parent directory structure if needed 
     destFile.getParentFile().mkdirs(); 

     try { 
      // extract file if not a directory 
      if (!entry.isDirectory()) { 
       // establish buffer for writing file 
       byte data[] = new byte[BUFFER]; 

       // write the current file to disk 
       FileOutputStream fos = new FileOutputStream(destFile); 
       BufferedOutputStream dest = new BufferedOutputStream(fos, 
         BUFFER); 

       // read and write until last byte is encountered 
       for (int bytesRead; (bytesRead = zis.read(data, 0, BUFFER)) != -1;) { 
        dest.write(data, 0, bytesRead); 
       } 
       dest.flush(); 
       dest.close(); 
      } 
     } catch (IOException ioe) { 
      ioe.printStackTrace(); 
     } 
    } 
    is.close(); 
} 

public static void main(String[] args) { 
    UnzipInputStream unzip = new UnzipInputStream(); 
    try { 
     InputStream fis = new FileInputStream(new File("test.zip")); 
     unzip.doUnzip(fis, "output"); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 
+0

文件内容是使用GZipOutputStream – 2012-02-10 08:46:40

+0

拉上你确定文件没有损坏?然后尝试在本地保存文件,并使用外部应用程序查看是否可以将其解压缩。如果可以的话,这是代码中的问题。如果不是,则文件已损坏,或者是另一种格式 – 2012-02-10 09:08:43