java解壓縮工具類

項目開發中,可能會用到對文件夾進行壓縮,生成壓縮文件。啥也不說了,直接上代碼,使用很方便,不過需要添加依賴jar包

<dependency>
<groupId>ant</groupId>
<artifactId>ant</artifactId>
<version>1.6.5</version>
</dependency>

代碼如下

package com.jd.heads.common.utils;

import java.io.BufferedInputStream;  
import java.io.DataInputStream;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
import java.io.IOException;  
  
import org.apache.tools.zip.ZipEntry;  
import org.apache.tools.zip.ZipOutputStream;  
import org.slf4j.Logger;  
import org.slf4j.LoggerFactory;  
  
 /**
  * java壓縮包操作工具類
  *
  * @ClassName: ZipUtils
  * @author caozhifei
  * @date 2015-3-25 下午02:32:55
  *
  */
public class ZipUtils {  
    private static final Logger log = LoggerFactory.getLogger(ZipUtils.class);  
          
    private ZipUtils(){};  
   /** 
     * 創建ZIP文件 
     * @param sourcePath 文件或文件夾路徑 
     * @param zipPath 生成的zip文件存在路徑(包括文件名) 
     */  
    public static void createZip(String sourcePath, String zipPath) {  
        FileOutputStream fos = null;  
        ZipOutputStream zos = null;  
        try {  
            fos = new FileOutputStream(zipPath);  
            zos = new ZipOutputStream(fos);  
            writeZip(new File(sourcePath), "", zos);  
        } catch (FileNotFoundException e) {  
            log.error("創建ZIP文件失敗",e);  
        } finally {  
            try {  
                if (zos != null) {  
                    zos.close();  
                }  
            } catch (IOException e) {  
                log.error("創建ZIP文件失敗",e);  
            }  
  
        }  
    }  
      
    private static void writeZip(File file, String parentPath, ZipOutputStream zos) {  
        if(file.exists()){  
            //處理文件夾  
            if(file.isDirectory()){  
                parentPath+=file.getName()+File.separator;  
                File [] files=file.listFiles();  
                for(File f:files){  
                    writeZip(f, parentPath, zos);  
                }  
            }else{  
                FileInputStream fis=null;  
                DataInputStream dis=null;  
                try {  
                    fis=new FileInputStream(file);  
                    dis=new DataInputStream(new BufferedInputStream(fis));  
                    ZipEntry ze = new ZipEntry(parentPath + file.getName());  
                    zos.putNextEntry(ze);  
                    //添加編碼,如果不添加,當文件以中文命名的情況下,會出現亂碼  
                    // ZipOutputStream的包一定是apache的ant.jar包。JDK也提供了打壓縮包,但是不能設置編碼  
                    zos.setEncoding("GBK");  
                    byte [] content=new byte[1024];  
                    int len;  
                    while((len=fis.read(content))!=-1){  
                        zos.write(content,0,len);  
                        zos.flush();  
                    }  
                } catch (FileNotFoundException e) {  
                    log.error("創建ZIP文件失敗",e);  
                } catch (IOException e) {  
                    log.error("創建ZIP文件失敗",e);  
                }finally{  
                    try {  
                        if(dis!=null){  
                            dis.close();  
                        }  
                    }catch(IOException e){  
                        log.error("創建ZIP文件失敗",e);  
                    }  
                }  
            }  
        }  
    }      
    public static void main(String[] args) {  
        //測試把F盤下的所有文件打包壓縮成sql.zip文件放在F盤根目錄下  
        ZipUtils.createZip("D:/header", "D:/header/測試.zip");  
          
    }  
}  

<pre name="code" class="java">GZIP方式解壓縮工具類



package com.jd.crius.common.util;

import org.springframework.util.FileCopyUtils;

import java.io.*;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * GZIP工具
 *
 * @author <a href="mailto:[email protected]">caozhifei</a>
 * @since 1.0
 */
public class GZipUtils {

    public static final int BUFFER = 1024;
    public static final String EXT = ".gz";

    /**
     * 數據壓縮
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static byte[] compress(byte[] data) throws Exception {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 壓縮
        compress(bais, baos);
        byte[] output = baos.toByteArray();
        baos.flush();
        baos.close();
        bais.close();
        return output;
    }

    /**
     * 文件壓縮
     *
     * @param file
     * @throws Exception
     */
    public static void compress(File file) throws Exception {
        compress(file, true);
    }

    /**
     * 文件壓縮
     *
     * @param file
     * @param delete 是否刪除原始文件
     * @throws Exception
     */
    public static void compress(File file, boolean delete) throws Exception {
        FileInputStream fis = new FileInputStream(file);
        FileOutputStream fos = new FileOutputStream(file.getPath() + EXT);
        compress(fis, fos);
        fis.close();
        fos.flush();
        fos.close();
        if (delete) {
            file.delete();
        }
    }

    /**
     * 數據壓縮
     *
     * @param is
     * @param os
     * @throws Exception
     */
    public static void compress(InputStream is, OutputStream os)
            throws Exception {
        GZIPOutputStream gos = new GZIPOutputStream(os);
        int count;
        byte data[] = new byte[BUFFER];
        while ((count = is.read(data, 0, BUFFER)) != -1) {
            gos.write(data, 0, count);
        }
        gos.finish();
        gos.flush();
        gos.close();
    }

    /**
     * 文件壓縮
     *
     * @param path
     * @throws Exception
     */
    public static void compress(String path) throws Exception {
        compress(path, true);
    }

    /**
     * 文件壓縮
     *
     * @param path
     * @param delete 是否刪除原始文件
     * @throws Exception
     */
    public static void compress(String path, boolean delete) throws Exception {
        File file = new File(path);
        compress(file, delete);
    }

    /**
     * 數據解壓縮
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static byte[] decompress(byte[] data) throws Exception {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 解壓縮
        decompress(bais, baos);
        data = baos.toByteArray();
        baos.flush();
        baos.close();
        bais.close();
        return data;
    }

    /**
     * 文件解壓縮
     *
     * @param file
     * @throws Exception
     */
    public static void decompress(File file) throws Exception {
        decompress(file, true);
    }

    /**
     * 文件解壓縮
     *
     * @param file
     * @param delete 是否刪除原始文件
     * @throws Exception
     */
    public static void decompress(File file, boolean delete) throws Exception {
        FileInputStream fis = new FileInputStream(file);
        FileOutputStream fos = new FileOutputStream(file.getPath().replace(EXT,
                ""));
        decompress(fis, fos);
        fis.close();
        fos.flush();
        fos.close();
        if (delete) {
            file.delete();
        }
    }

    /**
     * 數據解壓縮
     *
     * @param is
     * @param os
     * @throws Exception
     */
    public static void decompress(InputStream is, OutputStream os)
            throws Exception {
        GZIPInputStream gis = new GZIPInputStream(is);
        int count;
        byte data[] = new byte[BUFFER];
        while ((count = gis.read(data, 0, BUFFER)) != -1) {
            os.write(data, 0, count);
        }
        gis.close();
    }

    /**
     * 文件解壓縮
     *
     * @param path
     * @throws Exception
     */
    public static void decompress(String path) throws Exception {
        decompress(path, true);
    }

    /**
     * 文件解壓縮
     *
     * @param path
     * @param delete 是否刪除原始文件
     * @throws Exception
     */
    public static void decompress(String path, boolean delete) throws Exception {
        File file = new File(path);
        decompress(file, delete);
    }

    public static void main(String[] args) {
        try {
            File file = null;
            file = new File("D:\\export\\data\\header.jd.local\\common\\config1\\life_globalService_utf8.html");
            byte[] data = FileCopyUtils.copyToByteArray(file);
            //byte[] data = "<div id=\"logo-2013\" class=\"ld\"><a href=\"http://www.jd.com/\" hidefocus=\"true\"><b></b><img src=\"http://misc.360buyimg.com/lib/img/e/logo-201305.png\" width=\"270\" height=\"60\" alt=\"京東\"></a></div>".getBytes();
            System.out.println("press 之前=" + data.length);
            long start = System.currentTimeMillis();
            byte[] result = GZipUtils.compress(data);
            long end = System.currentTimeMillis();
            System.out.println("press 之後=" + result.length + ";消耗時間毫秒:" + (end - start));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章