Java - Zip 输出流动态缓冲区大小
我正在开发一个应用程序,该应用程序从一个 zip 中获取文件并将它们放入另一个 zip 中,它对文件没问题,但如果源 zip 中存在目录,则会失败,并出现以下异常:
Exception in thread "main" java.util.zip.ZipException: invalid entry size (expected 1374 but got 1024 bytes)
我正在使用以下代码:
public static void ZipExtractToZip(File inZip, File outZip) throws IOException
{
ZipInputStream zis = new ZipInputStream(new FileInputStream(inZip));
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outZip)));
byte[] buffer = new byte[1024];
for (ZipEntry ze = zis.getNextEntry(); ze != null; ze = zis.getNextEntry())
{
zos.putNextEntry(ze);
for (int read = zis.read(buffer); read != -1; read = zis.read(buffer)) {
zos.write(buffer, 0, read);
}
zos.closeEntry();
}
zos.close();
zis.close();
}
我有尝试了不同的缓冲区大小,但这没有帮助,我需要一种方法来获取动态缓冲区大小。 欢迎提供示例和链接。
编辑:我更改了代码以使其可用
- Liam,Hachi Software 首席执行官
I'm working on application that takes files from one zip and put them in the other, its fine with files but if there is a dir in the source zip it fail with the following exception:
Exception in thread "main" java.util.zip.ZipException: invalid entry size (expected 1374 but got 1024 bytes)
I'm using the following code:
public static void ZipExtractToZip(File inZip, File outZip) throws IOException
{
ZipInputStream zis = new ZipInputStream(new FileInputStream(inZip));
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outZip)));
byte[] buffer = new byte[1024];
for (ZipEntry ze = zis.getNextEntry(); ze != null; ze = zis.getNextEntry())
{
zos.putNextEntry(ze);
for (int read = zis.read(buffer); read != -1; read = zis.read(buffer)) {
zos.write(buffer, 0, read);
}
zos.closeEntry();
}
zos.close();
zis.close();
}
I have tried different buffer sizes but that doesn't help, I need a way to get a dynamic buffer size.
Examples and links are welcome.
EDIT: I changed the code to make it usable
- Liam, Hachi Software CEO
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
移到
最内层循环之外,否则您将假设每个条目的长度不超过 1024 字节。
我猜您的目录是该大小的第一个条目。
顺便说一句,您也可以移动
到外循环之前,这样它就只创建一次。
Move
outside the inner most loop, otherwise you are assuming each entry is no more than 1024 bytes long.
I am guess your directory is the first entry to be that size.
BTW, You can also move
to before the outer loop so it is created only once.