Java操做zip-壓縮和解壓文件

1、說明

rar格式的壓縮包收費,java支持zip格式的壓縮和解壓java

2、工具類

import java.io.*;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
public class ZipUtils {
    private static final int  BUFFER_SIZE = 2 * 1024;
    /**
     * zip解壓
     * @param srcFile        zip源文件
     * @param destDirPath     解壓後的目標文件夾
     * @throws RuntimeException 解壓失敗會拋出運行時異常
     */
    public static void unZip(File srcFile, String destDirPath) throws RuntimeException {
        long start = System.currentTimeMillis();
        // 判斷源文件是否存在
        if (!srcFile.exists()) {
            throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
        }
        // 開始解壓
        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(srcFile);
            Enumeration<?> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                System.out.println("解壓" + entry.getName());
                // 若是是文件夾,就建立個文件夾
                if (entry.isDirectory()) {
                    String dirPath = destDirPath + "/" + entry.getName();
                    File dir = new File(dirPath);
                    dir.mkdirs();
                } else {
                    // 若是是文件,就先建立一個文件,而後用io流把內容copy過去
                    File targetFile = new File(destDirPath + "/" + entry.getName());
                    // 保證這個文件的父文件夾必需要存在
                    if(!targetFile.getParentFile().exists()){
                        targetFile.getParentFile().mkdirs();
                    }
                    targetFile.createNewFile();
                    // 將壓縮文件內容寫入到這個文件中
                    InputStream is = zipFile.getInputStream(entry);
                    FileOutputStream fos = new FileOutputStream(targetFile);
                    int len;
                    byte[] buf = new byte[BUFFER_SIZE];
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    // 關流順序,先打開的後關閉
                    fos.close();
                    is.close();
                }
            }
            long end = System.currentTimeMillis();
            System.out.println("解壓完成,耗時:" + (end - start) +" ms");
        } catch (Exception e) {
            throw new RuntimeException("unzip error from ZipUtils", e);
        } finally {
            if(zipFile != null){
                try {
                    zipFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 壓縮成ZIP 方法
     * @param srcFiles 須要壓縮的文件列表
     * @param out           壓縮文件輸出流
     * @throws RuntimeException 壓縮失敗會拋出運行時異常
     */
    public static void toZip(List<File> srcFiles , OutputStream out)throws Exception {
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null ;
        try {
            zos = new ZipOutputStream(out);
            for (File srcFile : srcFiles) {
                byte[] buf = new byte[BUFFER_SIZE];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1){
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                in.close();
            }
            long end = System.currentTimeMillis();
            System.out.println("壓縮完成,耗時:" + (end - start) +" ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils",e);
        }finally{
            if(zos != null){
                try {
                    zos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

3、使用工具類壓縮和解壓文件

import com.szfore.utils.ZipUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class TestZip {

    public static void main(String[] args) throws Exception{
        //testToZip();
        testUnzip();
    }

    /**
     * 測試壓縮文件
     */
    public static void testToZip() throws Exception {
        File file1 = new File("c:\\1.txt");
        File file2 = new File("c:\\2.txt");
        List<File> files = new ArrayList<File>();
        files.add(file1);
        files.add(file2);
        OutputStream out = new FileOutputStream("c:\\1.zip");
        ZipUtils.toZip(files,out);
    }

    /**
     * 測試解壓文件
     * @throws Exception
     */
    public static void testUnzip() throws Exception{
        File srcFile = new File("c:\\2.zip");
        String destDirPath = "c:\\";
        ZipUtils.unZip(srcFile,destDirPath);
    }
}
相關文章
相關標籤/搜索