How to get bytes/contents of each ZipFile entry from ZipInputStream without writing to outputstream?

拥有回忆 提交于 2020-01-13 03:37:09

问题


I am trying to get the bytes of a particular file from the zipped file input stream. I have the input stream data of the Zipped file. From this I am getting the ZipEntry and writing the contents of each ZipEntry to a output stream and returning the byte buffer. This will return the buffer size output stream, but not the contents of each particular file. Is there a way I can convert the FileOutputStream to bytes or directly read the bytes of each ZipEntry?

I need to return the ZipEntry contents as output. I dont want to write to a file but just get the contents of each zip entry.

Thank you for your help.

public final class ArchiveUtils {

private static String TEMP_DIR = "/tmp/unzip/";

public static byte[] unZipFromByteStream(byte[] data, String fileName) {

    ZipEntry entry = null;
    ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(data));
    File tempDirectory = ensureTempDirectoryExists(TEMP_DIR);
    try {
        while ((entry = zis.getNextEntry()) != null) {

            if (!entry.isDirectory()) {
                System.out.println("-" + entry.getName());

                File file = new File(tempDirectory + "/"+ entry.getName());

                if (!new File(file.getParent()).exists())
                    new File(file.getParent()).mkdirs();
                OutputStream out = new FileOutputStream(entry.getName());
                byte[] byteBuff = new byte[1024];
                int bytesRead = 0;
                while ((bytesRead = zis.read(byteBuff)) != -1)
                {
                    out.write(byteBuff, 0, bytesRead);
                }
                out.close();
                if(entry.getName().equals(fileName)){
                return byteBuff;
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;
}

private static File ensureTempDirectoryExists(String outputPath) {

    File outputDirectory = new File(outputPath);
    if (!outputDirectory.exists()) {
        outputDirectory.mkdir();
    }
    return outputDirectory;
}

}


回答1:


Use a java.io.ByteArrayOutputStream like so -

ByteArrayOutputStream out = null; // outside of your loop (for scope).

// where you have a FileOutputStream.
out = new ByteArrayOutputStream(); // doesn't use entry.getName(). 

and then you can

return (out == null) ? null : out.toByteArray();



回答2:


The way that you read from a file in a ZIP file is you read from the ZipInputStream while the last entry you got from getNextEntry is the entry you want to read from.



来源:https://stackoverflow.com/questions/20793781/how-to-get-bytes-contents-of-each-zipfile-entry-from-zipinputstream-without-writ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!