Java 解压缩文件的内容

Java 解压缩文件的内容,java,Java,我有一个应用程序,其中服务A将向服务B提供压缩数据,而服务B需要将其解压缩 服务A有一个公开方法getStream,它将ByteArrayInputStream作为输出,数据init是压缩数据 但是,将其传递给GzipInputStream不会产生Gzip格式的异常 InputStream ins = method.getInputStream(); GZIPInputStream gis = new GZIPInputStream(ins); 这是一个例外。当文件转储到服务A中时,数据被压缩

我有一个应用程序,其中服务A将向服务B提供压缩数据,而服务B需要将其解压缩

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

但是,将其传递给GzipInputStream不会产生Gzip格式的异常

InputStream ins = method.getInputStream();
GZIPInputStream gis = new GZIPInputStream(ins);
这是一个例外。当文件转储到服务A中时,数据被压缩。因此getInputStream提供压缩的数据

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

问候

Dheeraj Joshi

如果它已压缩,则必须使用
ZipInputstream

它确实取决于“zip”格式。有多种格式具有zip名称(zip、gzip、bzip2、lzip),不同的格式调用不同的解析器。


如果您使用的是zip,请尝试以下代码:

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

文件内容是使用GZIPOutputStream压缩的。您确定文件没有损坏吗?然后尝试在本地保存该文件,并使用外部应用程序查看是否可以解压缩该文件。如果可以,这是代码中的一个问题。如果没有,则文件已损坏,或者是另一种格式