15

我正在尝试将字节数组转换为 ZIP 文件。我使用以下代码获取字节:

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

但我现在的问题是将字节数组转换回 ZIP 文件 - 怎么做?

注意:指定的 ZIP 包含两个文件。

4

3 回答 3

30

要从字节中获取内容,您可以使用

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(); 
于 2011-12-03T10:51:14.417 回答
6

您可能正在寻找这样的代码:

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

现在您可以通过以下方式获取 zip 文件内容getNextEntry()

于 2011-12-03T10:52:06.350 回答
0

这是一个辅助方法

private fun getZipData(): ByteArray {
    val zipFile: File = getTempZipFile() // Return a zip File

    val encoded = Files.readAllBytes(Paths.get(zipFile.absolutePath))
    zipFile.delete() // If you wish to delete the zip file

    return encoded
}
于 2021-08-04T10:11:15.753 回答