简体   繁体   中英

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.

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.

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. 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 :

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 .

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 . 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. For some reason, some of the files contained within the zip had characters being dropped. 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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