zoukankan      html  css  js  c++  java
  • 将某个目录下的所有文件进行压缩

    /**
    * @project: Test
    * @author chenssy
    * @date 2013-7-28
    * @Description: 文件压缩工具类
    * 将指定文件/文件夹压缩成zip、rar压缩文件
    */
    class CompressedFileUtil {
    /**
    * 默认构造函数
    */
    public CompressedFileUtil(){

    }
    /**
    * @desc 将源文件/文件夹生成指定格式的压缩文件,格式zip
    * @param resourcesPath 源文件/文件夹
    * @param targetPath 目的压缩文件保存路径
    * @return void
    * @throws Exception
    */
    public void compressedFile(String resourcesPath,String targetPath) throws Exception{
    File resourcesFile = new File(resourcesPath); //源文件
    File targetFile = new File(targetPath); //目的
    //如果目的路径不存在,则新建
    if(!targetFile.exists()){
    targetFile.mkdirs();
    }

    String targetName = resourcesFile.getName()+".zip"; //目的压缩文件名
    FileOutputStream outputStream = new FileOutputStream(targetPath+"\"+targetName);
    ZipOutputStream out = new ZipOutputStream(outputStream);

    createCompressedFile(out, resourcesFile, null);

    out.close();
    }

    /**
    * @desc 生成压缩文件。
    * 如果是文件夹,则使用递归,进行文件遍历、压缩
    * 如果是文件,直接压缩
    * @param out 输出流
    * @param file 目标文件
    * @return void
    * @throws Exception
    */
    public void createCompressedFile(ZipOutputStream out,File file,String dir) throws Exception{
    //如果当前的是文件夹,则进行进一步处理
    if(file.isDirectory()){
    //得到文件列表信息
    File[] files = file.listFiles();
    //将文件夹添加到下一级打包目录
    if(dir!=null){//这个判断是防止打包出一个没有名字的空文件夹
    out.putNextEntry(new ZipEntry(dir+"/"));
    dir = dir.length() == 0 ? "" : dir +"/";
    }
    if(dir==null){//防止第一次下面调用dir是为空
    dir = "";
    }
    //循环将文件夹中的文件打包
    for(int i = 0 ; i < files.length ; i++){
    createCompressedFile(out, files[i], dir + files[i].getName()); //递归处理
    }
    }
    else{//当前的是文件,打包处理
    //文件输入流
    FileInputStream fis = new FileInputStream(file);

    out.putNextEntry(new ZipEntry(dir));
    out.setEncoding("utf8");
    //进行写操作
    int j = 0;
    byte[] buffer = new byte[1024];
    while((j = fis.read(buffer)) > 0){
    out.write(buffer,0,j);
    }
    //关闭输入流
    fis.close();
    }
    }



    测试:
    public static void main(String[] args) throws Exception {
    CompressedFileUtil compressedFileUtil = new CompressedFileUtil();
    compressedFileUtil.compressedFile("E:\aaa", "E:\wang");//param1.要压缩的目录,param2.压缩后存放的目录
    }
  • 相关阅读:
    day3 程序流程控制
    day2 程序流程控制
    String.prototype.formatWith
    未能找到文件“in oslyncsc.exe”
    Azure DocumentDB
    查询表中所有字段的最大长度(大数据情况)
    查询表中所有字段的最大长度
    linux开发
    sql server cvs 导入
    清除“远程桌面连接”的历史记录
  • 原文地址:https://www.cnblogs.com/wangjing666/p/7642141.html
Copyright © 2011-2022 走看看