java通过zip压缩文件夹或者单个文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xukaixun005/article/details/80941433
    /** 
     * @Description 
     * @author xukaixun
     * @param zipSavePath   压缩好的zip包存放路径
     * @param sourceFile    待压缩的文件(单个文件或者整个文件目录)
     * @return  
     */
    public static void zipCompress(String zipSavePath, File sourceFile){
        try{
          //创建zip输出流
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipSavePath));
            compress(zos, sourceFile, sourceFile.getName());
            zos.close();
        }
        catch(Exception e){
            logger.error("zip compress file exception: {}, zipSavePath={}, sourceFile={}", e, zipSavePath, sourceFile.getName());
        }
    }
    
    private static void compress(ZipOutputStream zos, File sourceFile, String fileName) throws Exception{
        if(sourceFile.isDirectory()){
            //如果是文件夹,取出文件夹中的文件(或子文件夹)
            File[] fileList = sourceFile.listFiles();
            if(fileList.length==0)//如果文件夹为空,则只需在目的地zip文件中写入一个目录进入点
            {
                zos.putNextEntry(new ZipEntry(fileName + "/"));
            }
            else//如果文件夹不为空,则递归调用compress,文件夹中的每一个文件(或文件夹)进行压缩
            {
                for(File file : fileList)
                {
                    compress(zos, file, fileName + "/" + file.getName());
                }
            }
        }else{
            if(!sourceFile.exists()){
                zos.putNextEntry(new ZipEntry("/"));
                zos.closeEntry();
            }else{
                //单个文件,直接将其压缩到zip包中
                zos.putNextEntry(new ZipEntry(fileName));
                FileInputStream fis = new FileInputStream(sourceFile);
                byte[] buf = new byte[1024];
                int len;
                //将源文件写入到zip文件中
                while((len=fis.read(buf))!=-1)
                {
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                fis.close();
            }
        }
    }
    
    public static void main(String[] args){
        File file = new File("E:\\规则文件\\广西\\NR\\");
        SimpleDateFormat  sdf =new SimpleDateFormat("yyyyMMddHHmmss");
        String timeDir = sdf.format(Calendar.getInstance().getTime());
        zipCompress("E:\\" + "test" + File.separator + timeDir + ".zip",file);
    }

猜你喜欢

转载自blog.csdn.net/xukaixun005/article/details/80941433