java 解压,压缩单个文件

// 压缩单个文件
public static void doZip(String srcpath, String zipName) throws IOException {
// 声明一个要压缩的文件
File srcfile = new File(srcpath);
if (!srcfile.exists()) {
System.err.println(“要压缩的文件不存在!”);
System.exit(1);
}

//判断父路径是否存在
File zfile=new File(zipName);
if (!zfile.getParentFile().exists()) {
zfile.getParentFile().mkdirs();//如果不存在创建父路径
}
// 封装要压缩的文件
InputStream in = new FileInputStream(srcfile);
// 封装压缩后的路径
FileOutputStream fos = new FileOutputStream(zipName); //
ZipOutputStream zout = new ZipOutputStream(fos);
// 设置一个缓冲数组
byte[] by = new byte[1024];
int len = 0;
//(默认-1) 设置压缩等级(0-9),9最高压缩比,比GZIP压缩比更大,但是速度比它慢;
//经过粗略测试,zip的7等级跟GZIP压缩比类似;
zout.setLevel(7);
// 创建ZIP条目。传入文件名(带尾缀)
ZipEntry zipEntry = new ZipEntry(srcfile.getName());
// 开始写入新的 ZIP文件条目并将流定位到条目数据的开始处
zout.putNextEntry(zipEntry);
// 每次读取1kb
while ((len = in.read(by)) != -1) {
zout.write(by, 0, len);
}
zout.closeEntry();
zout.flush();
zout.close();
in.close();
System.out.println(“压缩成功!”);
}

// 解压单个文件
public static void UnZip(String zipName) throws IOException{
File zipfile = new File(zipName);
if (!zipfile.exists()) {
System.err.println(“要解压的文件不存在!”);
System.exit(1);
}
FileInputStream fis=new FileInputStream(zipfile);
//封装待解压文件
ZipInputStream zis=new ZipInputStream(fis);
ZipEntry zip=zis.getNextEntry();
//获取待解压文件的父路径
String parent=zipfile.getParent();
//封装解压后的路径
FileOutputStream fos=new
FileOutputStream(parent+”/”+zip.getName());
byte by[]=new byte[1024];
int len;
while((len=zis.read(by))!=-1){
fos.write(by, 0, len);
}
fos.flush();
fos.close();
zis.closeEntry();
zis.close();
System.out.println(“解压成功!”);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值