java 操作zip文件_java操作zip文件

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();

}

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值