1. 程式人生 > >java實現將檔案或資料夾壓縮

java實現將檔案或資料夾壓縮

由於專案需要,所以在網上找了一下看看有沒有java的壓縮檔案的例子,結果找到了一個,可以作為工具類直接使用,現將它釋出出來

public class UtilZipFile {

    private File targetFile;

    public UtilZipFile(File targetFile) {
        this.targetFile = targetFile;
        if (targetFile.exists()){
            targetFile.delete();
        }
    }

    /**
     * 壓縮檔案
     * @param srcfile
     */
    public void zipFiles(File srcfile){
        ZipOutputStream outputStream=null;
        try {
            outputStream=new ZipOutputStream(new FileOutputStream(targetFile));
            if(srcfile.isFile()){
                zipFile(srcfile,outputStream,"");
            }else {
                File[] list = srcfile.listFiles();
                for (int i = 0; i < list.length; i++) {
                    compress(list[i], outputStream,"");
                }
            }
            System.out.println("壓縮完畢");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 壓縮單個檔案
     * @param srcfile
     * @param out
     * @param basedir
     */
    public void zipFile(File srcfile, ZipOutputStream out, String basedir) {
        if (!srcfile.exists())
            return;

        byte[] buf = new byte[1024];
        FileInputStream in = null;

        try {
            int len;
            in = new FileInputStream(srcfile);
            out.putNextEntry(new ZipEntry(basedir + srcfile.getName()));

            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null)
                    out.closeEntry();
                if (in != null)
                    in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 壓縮資料夾裡的檔案
     * @param file
     * @param out
     * @param basedir
     */
    private void compress(File file, ZipOutputStream out, String basedir) {
        /* 判斷是目錄還是檔案 */
        if (file.isDirectory()) {
            this.zipDirectory(file, out, basedir);
        } else {
            this.zipFile(file, out, basedir);
        }
    }

    /**
     * 壓縮資料夾
     * @param dir
     * @param out
     * @param basedir
     */
    public void zipDirectory(File dir, ZipOutputStream out, String basedir) {
        if (!dir.exists())
            return;

        File[] files = dir.listFiles();
        for (int i = 0; i < files.length; i++) {
            /* 遞迴 */
            compress(files[i], out, basedir + dir.getName() + "/");
        }
    }

}

呼叫:
 File f=new File("F:\\2017-06-07");
 new UtilZipFile(new File("F:\\"+f.getName()+".zip")).zipFiles(f);