【问题标题】:How can I convert byte array to ZIP file如何将字节数组转换为 ZIP 文件
【发布时间】:2012-01-12 02:52:30
【问题描述】:

我正在尝试将字节数组转换为 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 包含两个文件。

【问题讨论】:

  • 你到底想要什么?是否要将字节写回磁盘到 zip 文件中?还是您想阅读内容?您如何读取它们的字节尚未解码。
  • @ morja -> 是的,我想以 zip 文件的形式将字节写回磁盘。
  • 好吧,然后只需使用 FileOutputStream 将字节写回磁盘并将文件命名为 .zip。你不想写解压出来的文件吗?
  • @morja -> 是的,我尝试使用 FileOutputStream 但我无法获得确切的 zip 文件。
  • 我仍然不完全了解您想要做什么...您可以更新您的问题并逐步描述或举例说明您想要实现的目标吗?

标签: java zipfile


【解决方案1】:

这是一个辅助方法

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
}

【讨论】:

    【解决方案2】:

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

    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(); 
    

    【讨论】:

    • 是的,这有助于我获取 zip 文件中存在的条目名称。使用它我们只能读取内容。但是我们如何将它存储到磁盘。
    • 您可以从 zipStream 中读取字节,然后使用 FileOutputStream 将其写入。或者直接写一遍。查看我的更新。
    【解决方案3】:

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

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

    现在您可以通过getNextEntry()获取压缩文件内容

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-29
      • 2019-12-27
      • 2011-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多