packagezip;importjava.io.BufferedInputStream;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;importjava.util.Enumeration;importjava.util.zip.ZipEntry;importjava.util.zip.ZipFile;importjava.util.zip.ZipOutputStream;public classUpdateZip {private static final byte[] BUFFER = new byte[4096 * 1024];public static void main(String[] args) throwsException {//路径
String path = "f:";//待插入zip
String zipname = "a.zip";//待插入文件
String txtname = "c.txt";//构建zip和文件准确路径
String oldzip = path+"/"+zipname;//构建中转zip路径
String newzip = path+"/b.zip";
String txt= path+"/"+txtname;//获取文件
ZipFile war = new ZipFile(path+"/"+zipname);
ZipOutputStream append= new ZipOutputStream(newFileOutputStream(newzip));//将待插入zip中文件复制到中转zip中
copytonew(war,append,txtname);//往中转zip中插入待插入文件
insertnewfile(append,txt);
close(war,append);//删除原来zip
delete(oldzip);//将中转zip重命名为原来zip
rename(oldzip,newzip);
}public static voidclose(ZipFile war,ZipOutputStream append){try{
war.close();
append.close();
}catch(IOException e) {
e.printStackTrace();
}
}public static voiddelete(String oldzip){
File file= newFile(oldzip);
file.delete();
System.out.println("delete:"+oldzip);
}public static voidrename(String oldzip,String newzip){
File newfile= newFile(oldzip);
File file= newFile(newzip);
file.renameTo(newfile);
System.out.println("rename:"+oldzip+"------》"+newzip);
}public static voidinsertnewfile(ZipOutputStream append,String txt){
File file= newFile(txt);
FileInputStream fis= null;
BufferedInputStream bis= null;try{
fis= newFileInputStream(file);
bis= newBufferedInputStream(fis);
ZipEntry entry= newZipEntry(file.getName());
append.putNextEntry(entry);intlength;byte[] buffer = new byte[4096];while ((length = bis.read(buffer)) != -1) {
append.write(buffer,0, length);
System.out.println("insert:"+txt);
}
}catch(IOException e) {
e.printStackTrace();
}finally{try{
bis.close();
fis.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}public static void copy(InputStream input, OutputStream output) throwsIOException {intbytesRead;while ((bytesRead = input.read(BUFFER))!= -1) {
output.write(BUFFER,0, bytesRead);
}
}public static voidcopytonew(ZipFile war,ZipOutputStream append,String txtname){
Enumeration extends ZipEntry> entries =war.entries();while(entries.hasMoreElements()) {
ZipEntry e=entries.nextElement();if(!e.getName().equals(txtname)){
System.out.println("copy: " +e.getName());try{
append.putNextEntry(e);if (!e.isDirectory()) {
copy(war.getInputStream(e), append);
}
append.closeEntry();
}catch(IOException e1) {
e1.printStackTrace();
}
}
}
}
}