可能重复:
使用Java将文件附加到zip文件
我有一个包含几个文件夹的zip,但重要的是dir,里面是另一个名为folder和folder的文件夹,其中包含许多我需要能够更新的文件.
我现在有一个名为dir的zip之外的目录,并且是我需要更新的文件夹,因此路径是相同的.如何将这些文件更新到zip中?
棘手的部分是dir是zip的根目录,它包含很多文件夹而不仅仅是文件夹但我只需要更新文件夹中的文件我不能弄乱文件夹外的任何文件但仍然在DIR.
可以这样做吗?我知道这可以使用-u修饰符在bash中完成,但如果可能的话,我宁愿用java来做.
感谢您对此问题的任何帮助
只是为了更清楚
在Zip / dir /文件夹/ filestoupdate里面
在zip / dir/folder/filestomoveintozip之外
好吧,这里是最后一个方法,它是相同的方法我粘贴之前,我实际上从链接@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;
}
Run Code Online (Sandbox Code Playgroud)
感谢链接最终能够改进该方法,以便它可以添加不在根目录中的文件,现在我是一个快乐的露营者:)希望这也有助于其他人出去
编辑 我在该方法上工作了一些,以便它不仅可以附加到zip,而且还可以更新zip中的文件
使用这样的方法
File[] files = {new File("/path/to/file/to/update/in")};
addFilesToZip(new File("/path/to/zip"), files, "folder/dir/");
Run Code Online (Sandbox Code Playgroud)
你不会用/启动路径(最后一个变量),因为它不是如何在zip条目中列出的
| 归档时间: |
|
| 查看次数: |
5733 次 |
| 最近记录: |