通过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();
}
}
}
相关文章
详解Spring Boot 使用Spring security 集成CAS
本篇文章主要介绍了详解Spring Boot 使用Spring security 集成CAS,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2017-05-05Spring Boot 整合 Fisco Bcos的案例分析(区块链)
本篇文章介绍的 Spring Boot 整合 Fisco Bcos的案例,是在阿里云服务器上部署验证的。大家可根据自己的电脑环境,对比该案例进行开发即可,具体案例代码跟随小编一起看看吧2022-01-01
最新评论