How can I convert byte array to ZIP file

孤者浪人 提交于 2019-12-28 13:35:45

问题


I am trying to convert an array of bytes into a ZIP file. I got bytes using the following code:

byte[] originalContentBytes= new Verification().readBytesFromAFile(new File("E://file.zip"));

private byte[] readBytesFromAFile(File file) {
    int start = 0;
    int length = 1024;
    int offset = -1;
    byte[] buffer = new byte[length];
    try {
        //convert the file content into a byte array
        FileInputStream fileInuptStream = new FileInputStream(file);
        BufferedInputStream bufferedInputStream = new BufferedInputStream(
                fileInuptStream);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        while ((offset = bufferedInputStream.read(buffer, start, length)) != -1) {
            byteArrayOutputStream.write(buffer, start, offset);
        }

        bufferedInputStream.close();
        byteArrayOutputStream.flush();
        buffer = byteArrayOutputStream.toByteArray();
        byteArrayOutputStream.close();
    } catch (FileNotFoundException fileNotFoundException) {
        fileNotFoundException.printStackTrace();
    } catch (IOException ioException) {
        ioException.printStackTrace();
    }

    return buffer;
}

But my problem now is with converting the byte array back into a ZIP file - how can it be done?

Note : The specified ZIP contains two files.


回答1:


To get the contents from the bytes you can use

ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(bytes));
ZipEntry entry = null;
while ((entry = zipStream.getNextEntry()) != null) {

    String entryName = entry.getName();

    FileOutputStream out = new FileOutputStream(entryName);

    byte[] byteBuff = new byte[4096];
    int bytesRead = 0;
    while ((bytesRead = zipStream.read(byteBuff)) != -1)
    {
        out.write(byteBuff, 0, bytesRead);
    }

    out.close();
    zipStream.closeEntry();
}
zipStream.close(); 



回答2:


You probably are looking for code like this:

ZipInputStream z = new ZipInputStream(new ByteArrayInputStream(buffer))

now you can get the zip file contents via getNextEntry()



来源:https://stackoverflow.com/questions/8367126/how-can-i-convert-byte-array-to-zip-file

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