通过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();
}
}
}