gpt4 book ai didi

java - 生成一个空的 zip 文件 java

转载 作者:搜寻专家 更新时间:2023-11-01 01:17:59 25 4
gpt4 key购买 nike

我目前正在编写一个函数来创建一个 zip 文件,该文件将用于其他功能。下面是我的函数代码:

public void createZip(){

try{
String outfile = this.filename + ".zip";
//input file
FileInputStream input = new FileInputStream(this.filename);
//output file
ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(outfile));
//name the file inside the zip file
System.out.println(this.filename);
zip.putNextEntry(new ZipEntry(this.filename));

byte[] buffer = new byte[this.BUFFER];
int len;
//copy the file to the zip
while((len= input.read(buffer)) > 0){
System.out.println(len);
zip.write(buffer, 0, len);
}
zip.closeEntry();
zip.flush();
input.close();
zip.close();
this.filename += ".zip";
}
catch(IOException e){
e.printStackTrace();
}

}

我试过调试,但找不到问题的根源。该函数运行时没有任何其他问题,但生成的 zip 文件是一个空文件。

最佳答案

您必须使用 ZipOutputStream#closeEntry() 关闭条目在关闭输出流之前,或者从未确认条目已完全写入。

另外,ZipEntry的名称不能是整个路径;即,它应该是 dog.png 而不是 C:\Users\Admin\Documents\dog.png。此问题将毫无异常(exception)地通过,并将导致文件中的数据直接压缩到 zip 中,而不是作为压缩文件压缩到 zip 中。

关于java - 生成一个空的 zip 文件 java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11022801/

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