Java實現壓縮文件的方法

package Zip;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


/**
 * @author 犀角
 * @date 2019/10/28 16:16
 * @description
 */

public class Zip {
    /**
     * 壓縮文件夾到指定目錄(JDK)
     * @param srcDir 壓縮文件夾
     * @param targetDir 壓縮文件存放目錄
     * @param zipName 壓縮文件名字
     * @return
     */
    public static boolean toZip(String srcDir, String targetDir, String zipName)  {
        File src = new File(srcDir);
        if (!src.exists()) {
            //創建由這個抽象路徑名命名的目錄
            src.mkdirs();
        }
        //創建文件的抽象路徑名數組,抽象路徑名錶示的目錄
        File[] srcFiles=src.listFiles();
        if(srcFiles == null || srcFiles.length<1){
            System.out.println(srcDir+"目錄下沒有文件!");
            return false;
        }
        File zipFile = new File(targetDir + zipName);
        if (!zipFile.exists()){
            try {
                zipFile.createNewFile();
            } catch (IOException e) {
                System.out.println(targetDir + zipName + ".zip創建失敗!");
                return false;
            }
        }

        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fos = new FileOutputStream(zipFile);
            zos = new ZipOutputStream(new BufferedOutputStream(fos));
            byte[] bufs = new byte[1024*8];
            for (File file:srcFiles){
                ZipEntry zipEntry=new ZipEntry(file.getName());
                zos.putNextEntry(zipEntry);
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis,1024*8);
                int read = 0;
                while ((read = bis.read(bufs, 0, 1024*8)) !=-1){
                    zos.write(bufs,0,read);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(srcDir + "壓縮失敗!");
            return false;
        }finally {
            try {
                if (zos!=null){
                    zos.close();
                }
                if (fos!=null){
                    fos.close();
                }
                if (fis!=null){
                    fis.close();
                }
                if (bis!=null){
                    bis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }
}

 

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