zip文件 压缩与解压缩

来源:互联网 发布:淘宝客服聊天记录技巧 编辑:程序博客网 时间:2024/05/17 00:03

zip 工具类

sourceFilePath = D:\tomcat_portal\bin\portalMS\portalPackage\NJGD
File fileDir = new File(sourceFilePath);
 doZip(fileDir);
 public static void doZip(File file)
    {
        
        List<File> fileList = new ArrayList<File>();
        
        List<File> allFiles = (ArrayList<File>)searchFiles(file.getPath(),
                fileList);
        
        Object[] fileArray = allFiles.toArray();
        
        BufferedInputStream in = null;
        
        FileInputStream fis = null;
        
        ZipOutputStream zos = null;
        
        FileOutputStream fos = null;
        
        try
        {
            
            fos = new FileOutputStream(file.getParent() + File.separator
                    + file.getName() + ".zip");
            
            zos = new ZipOutputStream(new BufferedOutputStream(fos, BUFFER));
            
            zos.setLevel(9);
            
            byte[] data = new byte[BUFFER];
            
            for (int i = 0; i < fileArray.length; i++)
            {
                
                // 设置压缩文件入口entry,为被读取的文件创建压缩条目
                
                File tempFile = new File(fileArray[i].toString());
                
                String rootStr = file.getPath();
                
                String entryStr = null;
                
                // entry以相对路径的形式设置。以文件夹C:\temp例如temp\test.doc或者test.xls
                // 如果设置不当,会出现拒绝访问等错误
                
                // 分别处理单个文件/目录的entry
                
                if (rootStr.equals(tempFile.getPath()))
                {
                    
                    entryStr = tempFile.getName();
                    
                }
                else
                {
                    
                    entryStr = tempFile.getPath()
                            .substring((rootStr + File.separator).length());
                    
                }
                
                log(entryStr);
                
                ZipEntry entry = new ZipEntry(entryStr);
                
                zos.putNextEntry(entry);
                
                fis = new FileInputStream(tempFile);
                
                in = new BufferedInputStream(fis, BUFFER);
                
                int count;
                
                while ((count = in.read(data, 0, BUFFER)) != -1)
                {
                    
                    zos.write(data, 0, count);
                    
                }
                
            }
            
        }
        
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
        finally
        {
            try
            {
                
                if (fos != null)
                {
                    in.close();
                }
                if (fis != null)
                {
                    zos.close();
                }
                if (in != null)
                {
                    in.close();
                }
                if (zos != null)
                {
                    zos.close();
                }
                
            }
            catch (Exception e)
            {
                
                e.printStackTrace();
            }
        }
    }
    
    public static List<File> searchFiles(String sourceFilePath,
            List<File> fileList)
    {
        File fileDir = new File(sourceFilePath);
        
        if (fileDir.isDirectory())
        {
            
            File[] subfiles = fileDir.listFiles();
            
            for (int i = 0; i < subfiles.length; i++)
            {
                
                searchFiles(subfiles[i].getPath(), fileList);
                
            }
            
        }
        else
        {
            
            fileList.add(fileDir);
            
        }
        
        return fileList;
        
    }

    
package com.xxxx.dhm.portalMS.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
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.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import org.apache.commons.compress.archivers.ArchiveException;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.compress.utils.IOUtils;

import com.xxxx.dhm.portalMS.common.Constants;
import com.xxxx.dhm.portalMS.common.DebugLogHelper;

public class ZIPUtil
{
    
    private static final int BUFFER = 8192;
    
    private static final DebugLogHelper logger = new DebugLogHelper(ZIPUtil.class);
    
    public static final String DEF_FILE_FORMAT = "zip";
    
    public static final String DEF_ENCODING = "GBK";
    
    private static void log(String msg)
    {
        
        logger.excepFuncDebugLog(msg);
        
    }
    
    /**
     *
     * 压缩工具方法,支持中文
     * @param rootPath 需要压缩的文件/目录路径
     * @param zipPath 压缩后的路径
     * @throws ArchiveException
     * @throws IOException
     * @return void
     * @exception throws
     */
    public static void file2Zip(String rootPath, String zipPath)
    {
        ZipArchiveOutputStream zos = null;
        try
        {
            zos = (ZipArchiveOutputStream)new ArchiveStreamFactory().createArchiveOutputStream(DEF_FILE_FORMAT,
                    new FileOutputStream(zipPath));
            // or new ZipArchiveOutputStream(new FileOutputStream(path))
            zos.setEncoding(DEF_ENCODING);
            File file = new File(rootPath);
            if (!file.exists())
            {
                return;
            }
            
            File[] files = null;
            if (file.isDirectory())
            {
                files = file.listFiles();
                
            }
            else
            {
                files = new File[1];
                files[0] = file;
            }
            
            zipFile(zos, files, rootPath);
        }
        catch (Exception ae)
        {
            ae.printStackTrace();
        }
        finally
        {
            if (null != zos)
            {
                try
                {
                    zos.close();
                }
                catch (IOException ioe)
                {
                    ioe.printStackTrace();
                }
            }
        }
        
    }
    
    /**
     *
     * 循环压缩
     * @param zos
     * @param files
     * @param rootPath
     * @throws IOException
     * @return void
     * @exception throws
     */
    private static void zipFile(ZipArchiveOutputStream zos, File[] files,
            String rootPath) throws IOException
    {
        ZipArchiveEntry ze = null;
        for (File f : files)
        {
            if (!f.exists())
            {
                continue;
            }
            
            ze = new ZipArchiveEntry(getEntryName(f, rootPath));// 获取每个文件相对路径,作为在ZIP中路径
            zos.putArchiveEntry(ze);
            // folder
            if (ze.isDirectory())
            {
                zos.closeArchiveEntry();
                zipFile(zos, f.listFiles(), rootPath);
            }
            // file
            else
            {
                FileInputStream fis = new FileInputStream(f);
                IOUtils.copy(fis, zos, 1024 * 10);
                fis.close();
                zos.closeArchiveEntry();
            }
        }
    }
    
    /**
     *
     * 得到文件在压缩包中的路径
     * @param f
     * @param rootPath
     * @return
     * @return String
     * @exception throws
     */
    private static String getEntryName(File f, String rootPath)
    {
        String entryName;
        String fPath = f.getAbsolutePath();
        if (fPath.indexOf(rootPath) != -1)
        {
            entryName = fPath.substring(rootPath.length() + 1);
        }
        else
        {
            entryName = f.getName();
        }
        
        if (f.isDirectory())
        {
            // "/"后缀表示entry是文件夹
            entryName += Constants.FILE_SEPARATOR.getStringValue();
        }
        
        return entryName;
    }
    
    private static String getFileName(String filePath)
    {
        
        int index = filePath.indexOf(".");
        
        return filePath.substring(0, index);
        
    }
    
    public static void zip(String sourceFilePath)
    {
        
        File fileDir = new File(sourceFilePath);
        
        if (fileDir.exists())
        {
            
            log(fileDir.getPath() + " Starting Zip ...");
            
            long startTime = System.currentTimeMillis();
            
            doZip(fileDir);
            
            long endTime = System.currentTimeMillis();
            
            long costTime = endTime - startTime;
            
            log("Zip Success!");
            
            log("use time -- " + costTime + " millsec!");
            
        }
        else
        {
            
            log("can't find the File!");
            
        }
        
    }
    
    public static void unZip(String zipFilePath)
    {
        
        File fileDir = new File(zipFilePath);
        
        if (fileDir.exists())
        {
            
            log(fileDir.getPath() + " Starting UnZip ...");
            
            long startTime = System.currentTimeMillis();
            
            doUnZip(fileDir);
            
            long endTime = System.currentTimeMillis();
            
            long costTime = endTime - startTime;
            
            log("UnZip Success!");
            
            log("use time -- " + costTime + " millsec!");
            
        }
        else
        {
            
            log("can't find the File!");
            
        }
        
    }
    
    public static void doZip(File file)
    {
        
        List<File> fileList = new ArrayList<File>();
        
        List<File> allFiles = (ArrayList<File>)searchFiles(file.getPath(),
                fileList);
        
        Object[] fileArray = allFiles.toArray();
        
        BufferedInputStream in = null;
        
        FileInputStream fis = null;
        
        ZipOutputStream zos = null;
        
        FileOutputStream fos = null;
        
        try
        {
            
            fos = new FileOutputStream(file.getParent() + File.separator
                    + file.getName() + ".zip");
            
            zos = new ZipOutputStream(new BufferedOutputStream(fos, BUFFER));
            
            zos.setLevel(9);
            
            byte[] data = new byte[BUFFER];
            
            for (int i = 0; i < fileArray.length; i++)
            {
                
                // 设置压缩文件入口entry,为被读取的文件创建压缩条目
                
                File tempFile = new File(fileArray[i].toString());
                
                String rootStr = file.getPath();
                
                String entryStr = null;
                
                // entry以相对路径的形式设置。以文件夹C:\temp例如temp\test.doc或者test.xls
                // 如果设置不当,会出现拒绝访问等错误
                
                // 分别处理单个文件/目录的entry
                
                if (rootStr.equals(tempFile.getPath()))
                {
                    
                    entryStr = tempFile.getName();
                    
                }
                else
                {
                    
                    entryStr = tempFile.getPath()
                            .substring((rootStr + File.separator).length());
                    
                }
                
                log(entryStr);
                
                ZipEntry entry = new ZipEntry(entryStr);
                
                zos.putNextEntry(entry);
                
                fis = new FileInputStream(tempFile);
                
                in = new BufferedInputStream(fis, BUFFER);
                
                int count;
                
                while ((count = in.read(data, 0, BUFFER)) != -1)
                {
                    
                    zos.write(data, 0, count);
                    
                }
                
            }
            
        }
        
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
        finally
        {
            try
            {
                
                if (fos != null)
                {
                    in.close();
                }
                if (fis != null)
                {
                    zos.close();
                }
                if (in != null)
                {
                    in.close();
                }
                if (zos != null)
                {
                    zos.close();
                }
                
            }
            catch (Exception e)
            {
                
                e.printStackTrace();
            }
        }
    }
    
    public static void doUnZip(File file)
    {
        
        try
        {
            final int BUFFER = 2048;
            
            BufferedOutputStream dest = null;
            
            FileInputStream fis = new FileInputStream(file);
            
            CheckedInputStream checksum = new CheckedInputStream(fis,
                    new Adler32());
            
            ZipInputStream zis = new ZipInputStream(new BufferedInputStream(
                    checksum));
            
            ZipEntry entry;
            
            while ((entry = zis.getNextEntry()) != null)
            {
                
                log("Extracting: " + entry);
                
                int count;
                
                byte[] data = new byte[BUFFER];
                
                log("unzip to " + getFileName(file.getPath()));
                
                FileOutputStream fos = new FileOutputStream(
                        getFileName(file.getPath()) + File.separator
                                + newDir(file, entry.getName()));
                
                dest = new BufferedOutputStream(fos, BUFFER);
                
                while ((count = zis.read(data, 0, BUFFER)) != -1)
                {
                    
                    dest.write(data, 0, count);
                    
                }
                
                dest.flush();
                
                dest.close();
            }
            
            zis.close();
            
            System.out.println("Checksum: " + checksum.getChecksum().getValue());
            
        }
        catch (Exception e)
        {
            
            e.printStackTrace();
            
        }
        
    }
    
    public static List<File> searchFiles(String sourceFilePath,
            List<File> fileList)
    {
        File fileDir = new File(sourceFilePath);
        
        if (fileDir.isDirectory())
        {
            
            File[] subfiles = fileDir.listFiles();
            
            for (int i = 0; i < subfiles.length; i++)
            {
                
                searchFiles(subfiles[i].getPath(), fileList);
                
            }
            
        }
        else
        {
            
            fileList.add(fileDir);
            
        }
        
        return fileList;
        
    }
    
    @SuppressWarnings("static-access")
    private static String newDir(File file, String entryName)
    {
        
        String rootDir = getFileName(file.getPath());
        
        log("root:" + rootDir);
        
        int index = entryName.lastIndexOf("\\");
        
        String dirStr = new File(rootDir).getParent();
        
        log(dirStr);
        
        if (index != -1)
        {
            String path = entryName.substring(0, index);
            
            log("new Dir:" + rootDir + file.separator + path);
            
            boolean b = new File(rootDir + file.separator + path).mkdirs();
            
            if (b)
            {
                logger.excepFuncDebugLog("Successfully created ...");
            }
            
            log("entry:" + entryName.substring(0, index));
            
        }
        
        else
        {
            boolean flag = new File(rootDir).mkdirs();
            
            if (flag)
            {
                logger.excepFuncDebugLog("Successfully created ...");
            }
            
            log("entry:" + entryName);
        }
        
        return entryName;
        
    }
    
    /**
     *
     * zip文件解压,支持中文
     * @param zipFile zip文件
     * @param baseDir 解压到的根目录
     * @return
     * @throws IOException
     * @return boolean
     * @exception throws
     */
    public static boolean unZipSupportChinese(File zipFile, String baseDir)
            throws IOException
    {
        DefUnZipHandler handler = new DefUnZipHandler(zipFile);
        handler.setBaseDir(baseDir);
        return handler.unZip();
    }
}


0 0
原创粉丝点击