gpt4 book ai didi

java - 如何将字节数组转换为 ZIP 文件

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:04:41 25 4
gpt4 key购买 nike

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

最佳答案

要从你可以使用的字节中获取内容

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

关于java - 如何将字节数组转换为 ZIP 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8367126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com