java 文件压缩/解压缩

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/** 
 * 将文件夹下面的文件 打包成zip压缩文件 
 *  
 * @author zsl
 * 
 */ 
public class FileToZip {

    private static Log log = LogFactory.getLog(FileToZip.class);
    static final int BUFFER = 1024*10; 

    private FileToZip(){}

    /** 
     * 将存放在sourceFilePath目录下的源文件,打包成fileName名称的zip文件,并存放到zipFilePath路径下 
     * @param sourceFilePath :待压缩的文件路径 
     * @param zipFilePath :压缩后存放路径 
     * @param fileName :压缩后文件的名称 
     * @return 
     */  
    public static String zip(String sourceFilePath,String zipFilePath,String fileName) {   
        FileOutputStream fout = null;  
        ZipOutputStream zout = null;
        File sourceFile = new File(sourceFilePath);  
        if (!sourceFile.exists()) {   
            log.info(("待压缩的文件目录:"+sourceFilePath+"不存在!"));
            return "待压缩内容不存在";
        }else{
            try { 
                File dirfile = new File(zipFilePath);
                if(!dirfile.exists()){
                    dirfile.mkdirs();
                }
                String filePath = zipFilePath + File.separator + fileName +".zip";
                File file = new File(filePath);
                fout = new FileOutputStream(file);     
                CheckedOutputStream cos = new CheckedOutputStream(fout,new CRC32());     
                zout = new ZipOutputStream(cos);  
                compress(sourceFile, zout, "");     
                zout.close(); 
                return filePath;
            } catch (Exception e) {     
                throw new RuntimeException(e);     
            }  
        }
    }  

    /** 
     * 将多个名称为pathNamde的目录或文件打包成fileName名称的zip文件,并存放到zipFilePath路径下 
     * @param pathName :待压缩的目录或文件路径 
     * @param zipFilePath :压缩后存放路径 
     * @param fileName :压缩后文件的名称 
     * @return 
     */  
    public static String mulitzip(String zipFilePath,String fileName,String... pathName) {   
        ZipOutputStream zout = null;    
        FileOutputStream fout = null;
        try {    
            String filePath = zipFilePath + File.separator + fileName +".zip";
            File file = new File(filePath);
            File dirfile = new File(zipFilePath);
            if(!dirfile.exists()){
                dirfile.mkdirs();
            }
            fout = new FileOutputStream(file);
            CheckedOutputStream cos = new CheckedOutputStream(fout,new CRC32());     
            zout = new ZipOutputStream(cos);     
            String basedir = "";   
            for (int i=0;i<pathName.length;i++){  
                compress(new File(pathName[i]), zout, basedir);     
            }  
            zout.close();  
            return filePath;
        } catch (Exception e) {     
            throw new RuntimeException(e);     
        }   
    }     

    /** 判断是目录还是文件 */    
    private static void compress(File file, ZipOutputStream out, String basedir) {     
        if (file.isDirectory()) {     
            zipDirectory(file, out, basedir);     
        } else {     
            zipFile(file, out, basedir);     
        }     
    } 

     /** 压缩一个目录 */    
    private static void zipDirectory(File dir, ZipOutputStream out, String basedir) {     
        if (!dir.exists()) {
            log.info(("待压缩的文件目录:"+dir.getName()+"不存在!"));
            return;   
        }
        File[] files = dir.listFiles();
        String path =basedir + dir.getName() + "/";
        /*判断若是空目录,执行压缩*/
        if(null == files || files.length == 0){
            ZipEntry entry = new ZipEntry(path);     
            try {
                out.putNextEntry(entry);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            for (int i = 0; i < files.length; i++) {     
                /* 递归 */    
                compress(files[i], out, path);     
            } 
        }
    }     

    /** 压缩一个文件 */    
    private static void zipFile(File file, ZipOutputStream out, String basedir) {     
        if (!file.exists()) {     
            log.info(("待压缩的文件:"+file.getName()+"不存在!"));
            return;     
        }     
        try {    
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));     
            ZipEntry entry = new ZipEntry(basedir + file.getName());     
            out.putNextEntry(entry);     
            int count;     
            byte data[] = new byte[BUFFER];     
            while ((count = bis.read(data, 0, BUFFER)) != -1) {     
                out.write(data, 0, count);     
            }     
            bis.close();  
        } catch (Exception e) {     
            throw new RuntimeException(e);     
        }     
    }  

    /** 
     * 解压,只解压一次zip文件
     * @param zipSourceFile :待解压的zip文件路径
     * @param destPath : 解压后存放路径 
     * @return 
     */ 
    public static void unZip(String zipSourceFile, String destPath) {
        log.info("开始解压");
        try {
            // 先指定压缩档的位置和档名,建立FileInputStream对象
            FileInputStream fins = new FileInputStream(zipSourceFile);
            // 将fins传入ZipInputStream中
            ZipInputStream zins = new ZipInputStream(fins);
            ZipEntry ze = null;
            byte[] ch = new byte[256];
            while ((ze = zins.getNextEntry()) != null) {
                log.info("当前得到文件名 = " + ze.getName());
                File zfile = new File(File.separator + destPath + File.separator + ze.getName());
                File fpath = new File(zfile.getParentFile().getPath());
                if (ze.isDirectory()) {
                    if (!zfile.exists())
                        zfile.mkdirs();
                    zins.closeEntry();
                }else {
                    if (!fpath.exists())
                        fpath.mkdirs();
                    FileOutputStream fouts = new FileOutputStream(zfile);
                    int i;
                    while ((i = zins.read(ch)) != -1)
                        fouts.write(ch, 0, i);
                    zins.closeEntry();
                    fouts.close();
                }
            }
            fins.close();
            zins.close();
            log.info("解压完成");
        }
        catch (Exception e) {
            log.info("unZip error:" + e.getMessage());
        }
    }

    /** 
     * 解压,解压zip文件内所有zip文件
     * @param zipSourceFile :待解压的zip文件路径
     * @param destPath : 解压后存放路径 
     * @return 
     */ 
    public static void unZipAll(String zipSourceFile, String destPath) {
        log.info("开始解压");
        List<File> allFile = new ArrayList<File>();
        String zipFileName = (new File(zipSourceFile)).getName();
        String zipName = zipFileName.substring(0, zipFileName.indexOf("."));
        destPath += File.separator + zipName; 
        try {
            // 先指定压缩档的位置和档名,建立FileInputStream对象
            FileInputStream fins = new FileInputStream(zipSourceFile);
            // 将fins传入ZipInputStream中
            ZipInputStream zins = new ZipInputStream(fins);
            ZipEntry ze = null;
            byte[] ch = new byte[256];
            while ((ze = zins.getNextEntry()) != null) {
                log.info("当前得到文件名 = " + ze.getName());
                File zfile = new File(File.separator + destPath + File.separator + ze.getName());
                File fpath = new File(zfile.getParentFile().getPath());
                if (ze.isDirectory()) {
                    if (!zfile.exists())
                        zfile.mkdirs();
                    zins.closeEntry();
                }else {
                    if (!fpath.exists())
                        fpath.mkdirs();
                    FileOutputStream fouts = new FileOutputStream(zfile);
                    int i;
                    while ((i = zins.read(ch)) != -1)
                        fouts.write(ch, 0, i);
                    zins.closeEntry();
                    fouts.close();
                    if(zfile.getName().endsWith(".zip")){
                        allFile.add(zfile);
                        String srcFile = zfile.getPath();
                        String tarPath = zfile.getParentFile().getPath();
                        unZipAll(srcFile, tarPath);
                    }
                }
            }
            fins.close();
            zins.close();
            log.info("解压完成");
        }
        catch (Exception e) {
            log.info("unZipAll error:" + e.getMessage());
        }
        for(File file : allFile){
            file.delete();
        }
    }

    /** 
     * 删除目录,并递归删除目录下所有子元素
     * @param dir : 待删除的目录文件
     * @return 
     */ 
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空,可以删除
        return dir.delete();
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值