1. 程式人生 > >java壓縮資料夾和檔案例項

java壓縮資料夾和檔案例項

package com.cn;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


/**
 * 壓縮.zip檔案類
 * 建立者    :  xxx
 * 建立日期: 2018年06月29日
 * */
public class ZipCompressorByAnt {
private static final int BUFFER_SIZE = 2 * 1024;


       /**
          * @param srcDir 壓縮資料夾路徑
          * @param out 壓縮檔案輸出流
          * @param KeepDirStructure 是否保留原來的目錄結構,
          *  true:保留目錄結構;
          *  false:所有檔案跑到壓縮包根目錄下(注意:不保留目錄結構可能會出現同名檔案,會壓縮失敗)
          * @throws RuntimeException 壓縮失敗會丟擲執行時異常
          */

          public static boolean toZip(String[] srcDir, String outDir,boolean KeepDirStructure) 

               throws RuntimeException, Exception {

                  OutputStream out = new FileOutputStream(new File(outDir));
                  long start = System.currentTimeMillis();
                  ZipOutputStream zos = null;
                  try {
                       zos = new ZipOutputStream(out);
                       List<File> sourceFileList = new ArrayList<File>();
                       for (String dir : srcDir) {
                            File sourceFile = new File(dir);
                            sourceFileList.add(sourceFile);
                       }
                      compress(sourceFileList, zos, KeepDirStructure);
                      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 (IOException e) {
                                  e.printStackTrace();
                             }
                        }
                    }
            }


         /**
           * 遞迴壓縮方法
           * @param sourceFile 原始檔
           * @param zos zip輸出流
           * @param name 壓縮後的名稱
           * @param KeepDirStructure 是否保留原來的目錄結構,
           *          true:保留目錄結構;
           *          false:所有檔案跑到壓縮包根目錄下(注意:不保留目錄結構可能會出現同名檔案,會壓縮失敗)
           * @throws Exception
           */
           private static void compress(File sourceFile, ZipOutputStream zos,
               String name, boolean KeepDirStructure) throws Exception {
                   byte[] buf = new byte[BUFFER_SIZE];
                   if (sourceFile.isFile()) {
                          zos.putNextEntry(new ZipEntry(name));
                          int len;
                          FileInputStream in = new FileInputStream(sourceFile);
                          while ((len = in.read(buf)) != -1) {
                                 zos.write(buf, 0, len);
                           }
                         // Complete the entry
                         zos.closeEntry();
                         in.close();
                    } else {
                         File[] listFiles = sourceFile.listFiles();
                         if (listFiles == null || listFiles.length == 0) {
                                if (KeepDirStructure) {
                                       zos.putNextEntry(new ZipEntry(name + "/"));
                                       zos.closeEntry();
                                }
                         } else {
                                for (File file : listFiles) {
                                      if (KeepDirStructure) {
                                           compress(file, zos, name + "/" + file.getName(),
                                           KeepDirStructure);
                                      } else {
                                           compress(file, zos, file.getName(), KeepDirStructure);

                                      }

                                 }                  

                          }
                    }
            }


            private static void compress(List<File> sourceFileList,
                ZipOutputStream zos, boolean KeepDirStructure) throws Exception {
                byte[] buf = new byte[BUFFER_SIZE];
                for (File sourceFile : sourceFileList) {
                         String name = sourceFile.getName();
                         if (sourceFile.isFile()) {
                                 zos.putNextEntry(new ZipEntry(name));
                                 int len;
                                 FileInputStream in = new FileInputStream(sourceFile);
                                 while ((len = in.read(buf)) != -1) {
                                            zos.write(buf, 0, len);
                                  }
                                  zos.closeEntry();
                                 in.close();
                           } else {
                                 File[] listFiles = sourceFile.listFiles();
                                 if (listFiles == null || listFiles.length == 0) {
                                         if (KeepDirStructure) {
                                                zos.putNextEntry(new ZipEntry(name + "/"));
                                                zos.closeEntry();
                                         }
                                 } else {
                                         for (File file : listFiles) {
                                                if (KeepDirStructure) {
                                                       compress(file, zos, name + "/" + file.getName(),
                                                       KeepDirStructure);
                                                 } else {
                                                       compress(file, zos, file.getName(),
                                                       KeepDirStructure);
                                                 }
                                          }
                                 }
                           }
                    }

            }

    public static void main(String[] args) throws Exception{
                String pathFile="E:\\Files";//資料夾路徑
    String mainXmlPath="E:\\1.xml";//檔案路徑
    String metaXmlPath="E:\\2.xml";//檔案路徑
                String[] srcDir = { pathFile,mainXmlPath,metaXmlPath};
                String outDir="E:\\mytest.zip";//壓縮後的.zip路徑
                toZip(srcDir, outDir, true);
}

}

壓縮前效果圖:


壓縮後效果圖:


相關推薦

java壓縮資料檔案例項

package com.cn;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.i

Java刪除資料其子檔案檔案的拷貝剪下

   1、遞迴刪除目錄下的所有檔案及子目錄下所有檔案 //遞迴刪除目錄下的所有檔案及子目錄下所有檔案 public static boolean deleteDir(File dir) { if (dir.isDirectory()) {

java 同時建立多個資料檔案

public void demo1() { try { File dir = new File("d:\\abc\\bcd"); if (!dir.exists()) { dir.mkdirs(); } File file = new

JAVA如何建立資料檔案並可以追加寫入txt

public static void createFile(String filePath1,String fileName,StringBuffer stringBuffer) throws IOException {         Stri

java拷貝資料android設定檔案許可權

拷貝資料夾的程式碼:  public boolean copy(String file1,String file2) {                    File in=new File(file1);                    File out=new

Java檔案IO學習筆記(五)-刪除資料檔案

本例項介紹如何驗證傳入路徑是否正確、如何刪除系統上的檔案或資料夾,包括刪除資料夾下的所有檔案。 刪除檔案與資料夾的技術要點如下: 1.File的delete()方法刪除檔案或資料夾。 2.當File指向一個資料夾時,必須保證資料夾下面的子檔案或子目錄為空,

JAVA之File類 獲取一個目錄下的所有資料檔案,包括子資料檔案

package ioTest.io3; import java.io.File; /* * 獲取一個目錄下的所有資料夾和檔案,包括子資料夾和子檔案 。 * 並將資料夾和檔名稱列印在控制檯上面。並且要顯示檔案目錄的層級 * 注:運用了遞迴的演算法。 */ public

Java 判斷資料檔案是否存在,不存在則建立

1、判斷檔案是否存在,不存在建立檔案 File file=new File("C:\\Users\\QPING\\Desktop\\JavaScript\\2.htm"); if(!file.exists()) { try { file.c

docker部署nginx並且掛載資料檔案

轉載來源:https://blog.csdn.net/qq_26614295/article/details/80505246 這段時間在研究docker,在部署nginx時遇到了坑,最主要的問題是在掛載檔案和資料夾的時候不知道怎麼掛載,經過反覆實驗以及檢視網上的教程,先總結如下: 1首先p

【筆記】window下 使用c++遍歷資料及其子資料檔案,並列印檔案路徑及各檔案內容

這兩天一直在學習如何使用c++遍歷資料夾、讀取檔案內容和寫入檔案。 話不多說,直接上程式碼 /** 檔案功能:遞迴遍歷資料夾,遍歷資料夾及其子資料夾和檔案.列印資料夾名稱、檔名稱和檔案數目*** 參考:https://www.cnblogs.com/collectionne/p/679230

(圖文)SVN檔案/資料圖示顏色不顯示問題解決辦法、SVN資料檔案狀態圖示顯示不正常

svn檢出的資料夾上沒有綠色的對號,或者紅色的感嘆號標識。仍然是windows預設的資料夾。 解決方法: 首先,用win+R鍵開啟 執行 視窗,裡面輸入regedit(登錄檔),確定進入 首先我們找到localmachine,點選進入,下面找到software,展開下面的節點 在sof

【Tools】TortoiseGit資料檔案狀態圖示不顯示問題

00.目錄 01. 執行環境 TortoiseGit版本: TortoiseGit-2.6.0.0-64bit.msi Git版本: Git-2.16.2-64-bit.exe 02. 問題描述 首先在桌面新建一個資料夾叫“Project”

讀取資料檔案路徑簡單的小功能

using System.IO; //定義變數   private Stream myStream;  private void button2_Click(object sender, EventArgs e)         {

C/C++遍歷資料檔案

庫函式 包含標頭檔案 #include 用到資料結構_finddata_t,檔案資訊結構體的指標。 struct _finddata_t { unsigned attrib; //檔案屬性 time_t time_c

Qt總結之二:遍歷資料檔案目錄,並過濾獲取檔案資訊、字尾名、字首名(二)

前言 需要在特定目錄或磁碟下查詢特定檔案 一、篩選目錄 (一)單一目錄下遍歷,篩選特定檔案 QDir dir("./SaveFiles"); QFileInfoList list = dir.entryInfoList(); (二)裝置所有磁碟中遍歷 QF

Qt小程式(七)——獲取資料檔案路徑

目錄 前言 這篇博文躺在草稿箱裡很久了,一直沒有完成!主要時間一過,就忘記了原來要寫什麼 內容了!記得在哪裡看過這句話:今天的事如果不完成,或許你永遠都不會完成了!這裡把這篇博文就記錄Qt中讀取資料夾和檔案路徑。 QWidget/QDialo

C# FileSystemWatcher 在監控資料檔案時的用法概述

概述 最近學習FileSystemWatcher的用法,它主要是監控一個資料夾,當資料夾內的檔案要是有更改就要記錄下來,我就整理下我對FileSystemWatcher 的理解和用法. FileSystemWatcher 用法 在應用FileSyst

【Android】專案中資料檔案的作用

Table of Contents 資料夾的作用  檔案的作用    資料夾的作用  No. 資料夾 描述 1 src 存放

Qt總結之一:遍歷資料檔案目錄,並過濾獲取檔案資訊、字尾名、字首名(一)

一、採用遞迴和QDir實現資料夾下所有檔案遍歷的方法 #include <QDir> bool FindFile(const QString & path) {     QDir dir(path);   if (!dir.exists(

Qt總結之三:磁碟檔案操作、遍歷資料檔案目錄,並過濾獲取檔案資訊、字尾名、字首名(三)

前言 本節內容主要包括磁碟容量檢測、磁碟內指定或特定檔案的操作 話不多說,先上效果圖 共分為兩個部分,第一部分是檢測磁碟容量,第二部分是篩選磁碟內指定檔案(test.txt)或特定檔案(.txt / .png型別檔案) 獲取磁碟容量關鍵函式:【fileapi.h】