java简单实现压缩和解压功能

本文介绍了一个使用Java实现的压缩与解压缩工具类。该工具利用Ant库进行文件的ZIP压缩及解压缩操作,并提供了详细的错误日志记录。文中通过示例展示了如何对单个文件或文件夹进行压缩与解压缩。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Expand;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;
import java.io.File;
public class ZipUtil {
    private  final Project DEFAULT_PROJECT = new Project();
    private Logger log= LogManager.getLogger(ZipUtil.class.getName());
    public  void unZip(String orginFilePath, String  destFilePath) {
        try {
            File orgin=new File(orginFilePath);
File dest=new File(destFilePath);
Expand expand = new Expand();
expand.setProject(DEFAULT_PROJECT);
expand.setSrc(orgin);
expand.setDest(dest);
expand.execute();
} catch (Exception e) {
            log.error("解压文件时,出现异常 :",e);
}
    }

    public  void zip(String orginFilePath, String  destFilePath) {
        try {
            File orgin=new File(orginFilePath);
File dest=new File(destFilePath);
Zip zip = new Zip();
zip.setProject(DEFAULT_PROJECT);
zip.setDestFile(dest);
FileSet fs = new FileSet();
fs.setProject(DEFAULT_PROJECT);
fs.setDir(orgin);
            if(orgin.isDirectory()) fs.setDir(orgin);//设置压缩对象为文件夹
if(orgin.isFile()) fs.setFile(orgin);//设置压缩对象为文件
//    fs.setIncludes("**/*.java");
//    fs.setExcludes("**/*.xml");
zip.addFileset(fs);
zip.execute();
} catch (Exception e) {
            log.error("压缩文件时,出现异常 :", e);
}

    }

    /**
     * @param args
*/
public static void main(String[] args) {
        ZipUtil zipUtil=new ZipUtil();
//压缩
String orginPath2="d:\\\\sqlback\\d.sql" ;
String destPath2 ="d:\\\\sqlback\\d.zip";
System.out.println("----------zip starting-----------");
zipUtil.zip(orginPath2, destPath2);
System.out.println("----------zip success-----------");
//解压
String orginPath="d:\\\\sqlback\\d.zip";
String  destPath="d:\\\\sqlback";
zipUtil.unZip(orginPath, destPath);
System.out.println("----------un zip -----------");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值