java實現zip壓縮檔/檔案夾

來源:互聯網
上載者:User
由於java.util.zip.ZipOutputStream有中文亂碼問題,所以採用org.apache.tools.zip.ZipOutputStream。 
以下是代碼: 
import java.io.BufferedInputStream;  import java.io.File;  import java.io.FileInputStream;  import java.io.FileOutputStream;  import java.util.zip.CRC32;  import java.util.zip.CheckedOutputStream;  import org.apache.log4j.Logger;import org.apache.tools.zip.ZipEntry;  import org.apache.tools.zip.ZipOutputStream;  /** * @ClassName: ZipCompressor * @CreateTime Apr 28, 2013 1:12:16 PM * @author : Mayi * @Description: 壓縮檔的通用工具類-採用org.apache.tools.zip.ZipOutputStream實現,較複雜。 * */public class ZipCompressor {private Logger logger = Logger.getLogger(ZipCompressor.class);    static final int BUFFER = 8192;      private File zipFile;          /**     * 壓縮檔建構函式     * @param pathName 壓縮的檔案存放目錄     */    public ZipCompressor(String pathName) {          zipFile = new File(pathName);      }        /**     * 執行壓縮操作     * @param srcPathName 被壓縮的檔案/檔案夾     */    public void compressExe(String srcPathName) {          File file = new File(srcPathName);          if (!file.exists()){        throw new RuntimeException(srcPathName + "不存在。");          }        try {              FileOutputStream fileOutputStream = new FileOutputStream(zipFile);              CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream,new CRC32());              ZipOutputStream out = new ZipOutputStream(cos);              String basedir = "";              compressByType(file, out, basedir);              out.close();          } catch (Exception e) {         e.printStackTrace();        logger.error("執行壓縮操作時發生異常:"+e);            throw new RuntimeException(e);          }      }        /**     * 判斷是目錄還是檔案,根據類型(檔案/檔案夾)執行不同的壓縮方法     * @param file      * @param out     * @param basedir     */    private void compressByType(File file, ZipOutputStream out, String basedir) {          /* 判斷是目錄還是檔案 */          if (file.isDirectory()) {          logger.info("壓縮:" + basedir + file.getName());              this.compressDirectory(file, out, basedir);          } else {          logger.info("壓縮:" + basedir + file.getName());              this.compressFile(file, out, basedir);          }      }        /**     * 壓縮一個目錄     * @param dir     * @param out     * @param basedir     */    private void compressDirectory(File dir, ZipOutputStream out, String basedir) {          if (!dir.exists()){         return;          }                   File[] files = dir.listFiles();          for (int i = 0; i < files.length; i++) {              /* 遞迴 */          compressByType(files[i], out, basedir + dir.getName() + "/");          }      }        /**     * 壓縮一個檔案     * @param file     * @param out     * @param basedir     */    private void compressFile(File file, ZipOutputStream out, String basedir) {          if (!file.exists()) {              return;          }          try {              BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));              ZipEntry entry = new ZipEntry(basedir + file.getName());              out.putNextEntry(entry);              int count;              byte data[] = new byte[BUFFER];              while ((count = bis.read(data, 0, BUFFER)) != -1) {                  out.write(data, 0, count);              }              bis.close();          } catch (Exception e) {              throw new RuntimeException(e);          }      }  }

後來發現原來可以用ant中的org.apache.tools.ant.taskdefs.Zip來實現,更加簡單。
import java.io.File;  import org.apache.tools.ant.Project;  import org.apache.tools.ant.taskdefs.Zip;  import org.apache.tools.ant.types.FileSet;    /** * @ClassName: ZipCompressorByAnt * @CreateTime Apr 28, 2013 1:23:45 PM * @author : Mayi * @Description: 壓縮檔的通用工具類-採用ant中的org.apache.tools.ant.taskdefs.Zip來實現,更加簡單。 * */public class ZipCompressorByAnt {        private File zipFile;        /**     * 壓縮檔建構函式     * @param pathName 最終壓縮產生的壓縮檔:目錄+壓縮檔名.zip     */    public ZipCompressorByAnt(String finalFile) {          zipFile = new File(finalFile);      }            /**     * 執行壓縮操作     * @param srcPathName 需要被壓縮的檔案/檔案夾     */    public void compressExe(String srcPathName) {          File srcdir = new File(srcPathName);          if (!srcdir.exists()){            throw new RuntimeException(srcPathName + "不存在。");          }                   Project prj = new Project();          Zip zip = new Zip();          zip.setProject(prj);          zip.setDestFile(zipFile);          FileSet fileSet = new FileSet();          fileSet.setProject(prj);          fileSet.setDir(srcdir);          //fileSet.setIncludes("**/*.java"); //包括哪些檔案或檔案夾 eg:zip.setIncludes("*.java");          //fileSet.setExcludes(...); //排除哪些檔案或檔案夾          zip.addFileset(fileSet);          zip.execute();      }  } 


測試一下 
Java代碼   package net.szh.zip;      public class TestZip {       public static void main(String[] args) {           ZipCompressor zc = new  ZipCompressor("E:\\szhzip.zip");           zc.compress("E:\\test");                      ZipCompressorByAnt zca = new ZipCompressorByAnt("E:\\szhzipant.zip");           zca.compress("E:\\test");       }   }  
參考自:ITeye

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.