简体   繁体   English

如何将 ZipInputStream 转换为 InputStream?

[英]How can I convert ZipInputStream to InputStream?

I have code, where ZipInputSream is converted to byte[], but I don't know how I can convert that to inputstream.我有代码,其中 ZipInputSream 转换为字节 [],但我不知道如何将其转换为输入流。

private void convertStream(String encoding, ZipInputStream in) throws IOException,
        UnsupportedEncodingException
{
    final int BUFFER = 1;
    @SuppressWarnings("unused")
    int count = 0;
    byte data[] = new byte[BUFFER];
    while ((count = in.read(data, 0, BUFFER)) != -1) 
    {
       // How can I convert data to InputStream  here ?                    
    }
}

Here is how I solved this problem.这是我解决这个问题的方法。 Now I can get single files from ZipInputStream to memory as InputStream.现在我可以将单个文件从 ZipInputStream 获取到内存作为 InputStream。

private InputStream convertZipInputStreamToInputStream(ZipInputStream in, ZipEntry entry, String encoding) throws IOException
{
    final int BUFFER = 2048;
    int count = 0;
    byte data[] = new byte[BUFFER];
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    while ((count = in.read(data, 0, BUFFER)) != -1) {
        out.write(data);
    }       
    InputStream is = new ByteArrayInputStream(out.toByteArray());
    return is;
}

Please find below example of function that will extract all files from ZIP archive.请在下面找到将从 ZIP 存档中提取所有文件的函数示例。 This function will not work with files in subfolders:此功能不适用于子文件夹中的文件:

private static void testZip() {
    ZipInputStream zipStream = null;
    byte buff[] = new byte[16384];
    int readBytes;
    try {
        FileInputStream fis = new FileInputStream("./test.zip");
        zipStream = new ZipInputStream(fis);
        ZipEntry ze;
        while((ze = zipStream.getNextEntry()) != null) {
            if(ze.isDirectory()) {
                System.out.println("Folder : "+ze.getName());
                continue;//no need to extract
            }
            System.out.println("Extracting file "+ze.getName());
            //at this moment zipStream pointing to the beginning of current ZipEntry, e.g. archived file
            //saving file
            FileOutputStream outFile = new FileOutputStream(ze.getName());
            while((readBytes = zipStream.read(buff)) != -1) {
                outFile.write(buff, 0, readBytes);
            }
            outFile.close();                
        }

    } catch (Exception e) {
        System.err.println("Error processing zip file : "+e.getMessage());
    } finally {
        if(zipStream != null)
            try {
                zipStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
}

Below works for me for FileOutputStream :以下适用于FileOutputStream

try (ZipInputStream zin = new ZipInputStream(response.getInputStream())) {
        for (ZipEntry zipEntry = zin.getNextEntry(); zipEntry != null; zipEntry = zin.getNextEntry()) {
            File f = new File(dir, zipEntry.getName());
            try (FileOutputStream fout = new FileOutputStream(f)) {
                 int len;
                 byte[] buffer = new byte[1024];
                 while ((len = zin.read(buffer)) > 0) {
                     fout.write(buffer, 0, len);
                 }
                zin.closeEntry();
            }
        }
    }

ZipInputStream allows to read ZIP contents directly: iterate using getNextEntry() until you find the entry you want to read and then just read from the ZipInputStream . ZipInputStream允许直接读取 ZIP 内容:使用getNextEntry()进行迭代,直到找到要读取的条目,然后从ZipInputStream中读取。

If you don't want to just read ZIP content, but you need to apply an additional transform to the stream before passing to the next step, you can use PipedInputStream and PipedOutputStream .如果您不想只读取 ZIP 内容,但需要在传递到下一步之前对流应用额外的转换,则可以使用PipedInputStreamPipedOutputStream The idea would be similar to this (written from memory, might not even compile):这个想法将与此类似(从内存中编写,甚至可能无法编译):

import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public abstract class FilterThread extends Thread {
    private InputStream unfiltered;
    public void setUnfilteredStream(InputStream unfiltered) {
        this.unfiltered = unfiltered;
    }
    private OutputStream threadOutput;
    public void setThreadOutputStream(OutputStream threadOutput) {
        this.threadOutput = threadOutput;
    }    

    // read from unfiltered stream, filter and write to thread output stream
    public abstract void run();
}

...

public InputStream getFilteredStream(InputStream unfiltered, FilterThread filter) {
    PipedInputStream filteredInputStream = new PipedInputStream();
    PipedOutputStream threadOutputStream = new PipedOutputStream(filteredInputStream);

    filter.setUnfilteredStream(unfiltered);
    filter.setThreadOuptut(threadOutputStream);
    filter.start();

    return filteredInputStream;
}

...

public void clientCode() {
    ...
    ZipInputStream zis = ...;// get ZIP stream
    FilterThread filter = ...; // assign your implementation of FilterThread that transforms your ZipInputStream

    InputStream filteredZipInputStream = getFilteredStream(zis, filter);
    ...
}

The zip code is fairly easy but I had issues with returning ZipInputStream as Inputstream.邮政编码相当简单,但我在将 ZipInputStream 作为 Inputstream 返回时遇到了问题。 For some reason, some of the files contained within the zip had characters being dropped.出于某种原因,zip 中包含的某些文件的字符被丢弃。 The below was my solution and so far its been working.以下是我的解决方案,到目前为止它一直在工作。

private Map<String, InputStream> getFilesFromZip(final DataHandler dhZ,
        String operation) throws ServiceFault
{
    Map<String, InputStream> fileEntries = new HashMap<String, InputStream>();
    try
    {

        DataSource dsZ = dhZ.getDataSource();

        ZipInputStream zipIsZ = new ZipInputStream(dhZ.getDataSource()
                .getInputStream());

        try
        {
            ZipEntry entry;
            while ((entry = zipIsZ.getNextEntry()) != null)
            {
                if (!entry.isDirectory())
                {
                    Path p = Paths.get(entry.toString());
                    fileEntries.put(p.getFileName().toString(),
                            convertZipInputStreamToInputStream(zipIsZ));
                }

            }
        }
        finally
        {
            zipIsZ.close();
        }

    }
    catch (final Exception e)
    {
        faultLocal(LOGGER, e, operation);
    }

    return fileEntries;
}
private InputStream convertZipInputStreamToInputStream(
        final ZipInputStream in) throws IOException
{
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    IOUtils.copy(in, out);
    InputStream is = new ByteArrayInputStream(out.toByteArray());
    return is;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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