好吧,这是最后的方法,它与我之前粘贴的方法相同,我实际上是从 @Qwe 之前发布的链接中的 stackoverflow 主题获得的,但我添加了路径变量,以便它可以将文件添加到 zip 内的文件夹中
好吧,现在如何在上面的示例中使用它,我想将一个文件添加到另一个文件夹内的文件夹中,我将使用我在问题中的设置来做到这一点,如下所示
private void addFilesToZip(File source, File[] files, String path){
try{
File tmpZip = File.createTempFile(source.getName(), null);
tmpZip.delete();
if(!source.renameTo(tmpZip)){
throw new Exception("Could not make temp file (" + source.getName() + ")");
}
byte[] buffer = new byte[4096];
ZipInputStream zin = new ZipInputStream(new FileInputStream(tmpZip));
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(source));
for(int i = 0; i < files.length; i++){
InputStream in = new FileInputStream(files[i]);
out.putNextEntry(new ZipEntry(path + files[i].getName()));
for(int read = in.read(buffer); read > -1; read = in.read(buffer)){
out.write(buffer, 0, read);
}
out.closeEntry();
in.close();
}
for(ZipEntry ze = zin.getNextEntry(); ze != null; ze = zin.getNextEntry()){
if(!zipEntryMatch(ze.getName(), files, path)){
out.putNextEntry(ze);
for(int read = zin.read(buffer); read > -1; read = zin.read(buffer)){
out.write(buffer, 0, read);
}
out.closeEntry();
}
}
out.close();
tmpZip.delete();
}catch(Exception e){
e.printStackTrace();
}
}
private boolean zipEntryMatch(String zeName, File[] files, String path){
for(int i = 0; i < files.length; i++){
if((path + files[i].getName()).equals(zeName)){
return true;
}
}
return false;
}
感谢您的链接最终能够稍微改进该方法,以便它可以添加不在根目录中的文件,现在我是一个快乐的露营者:)希望这也能帮助其他人
EDIT我在该方法上做了更多工作,这样它不仅可以附加到 zip 中,还可以更新 zip 中的文件
使用这样的方法
File[] files = {new File("/path/to/file/to/update/in")};
addFilesToZip(new File("/path/to/zip"), files, "folder/dir/");
您不会以 / 开头路径(最后一个变量),因为这不是它在 zip 条目中列出的方式