通过java api实现解压缩zip示例
通过java api实现zip压缩格式的压缩与解压缩
package com.hongyuan.test;
import java.io.file;
import java.io.fileinputstream;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.outputstream;
import java.util.enumeration;
import java.util.zip.zipentry;
import java.util.zip.zipfile;
import java.util.zip.zipoutputstream;
public class ziptest {
public static void main(string[] args) throws ioexception {
unzip("bootstrap.zip");
zip("bootstrap_01.zip","bootstrap/css/bootstrap.css","bootstrap/css/bootstrap.min.css");
}
public static void unzip(string filename) throws ioexception{
//获取压缩文件对象
zipfile zf = new zipfile(filename);
//遍历文件条目
enumeration<? extends zipentry> items = zf.entries();
while (items.hasmoreelements()) {
zipentry item = items.nextelement();
string filepath = zf.getname().substring(0,
zf.getname().lastindexof("."))
+ file.separator + item.getname();
file filedir = new file(filepath.substring(0,
filepath.lastindexof("/")));
if (!filedir.exists()) {
filedir.mkdirs();
}
//从流中读取文件
outputstream out = new fileoutputstream(filepath);
inputstream in = zf.getinputstream(item);
byte[] temp = new byte[1024];
int len = 0;
while ((len = in.read(temp)) > 0) {
out.write(temp, 0, len);
}
in.close();
out.close();
}
zf.close();
}
public static void zip(string filename,string... files) throws ioexception{
//构造压缩文件输出流
zipoutputstream zos=new zipoutputstream(new fileoutputstream(filename));
for(int i=0,size=files.length;i<size;i++){
//创建压缩实体
zipentry entry=new zipentry(files[i].substring(files[i].lastindexof("/")+1));
zos.putnextentry(entry);
//将文件内容输出到压缩流中
inputstream is=new fileinputstream(files[i]);
int count=0;
byte[] buffer=new byte[1024];
while((count=is.read(buffer))>=0){
zos.write(buffer, 0, count);
}
zos.flush();
zos.closeentry();
is.close();
}
}
}
上一篇: 用python找出那些被“标记”的照片
下一篇: java堆排序概念原理介绍