檔案批量打包下載
阿新 • • 發佈:2018-11-10
package zy_cms_web;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipTest {
public static void main(String[] args) { // 需要壓縮的檔案--包括檔案地址和檔名 String[] path = { "E:\\DATA\\Log_File\\log1.txt", "E:\\DATA\\Log_File\\log2.txt" }; // 要生成的壓縮檔案地址和檔名稱 String desPath = "C:\\Users\\dancer\\Desktop\\DownLoad.zip"; File zipFile = new File(desPath); ZipOutputStream zipStream = null; FileInputStream zipSource = null; BufferedInputStream bufferStream = null; try { // 構造最終壓縮包的輸出流 zipStream = new ZipOutputStream(new FileOutputStream(zipFile)); for (int i = 0; i < path.length; i++) { File file = new File(path[i]); // 將需要壓縮的檔案格式化為輸入流 zipSource = new FileInputStream(file); // 壓縮條目不是具體獨立的檔案,而是壓縮包檔案列表中的列表項,稱為條目,就像索引一樣 ZipEntry zipEntry = new ZipEntry(file.getName()); // 定位該壓縮條目位置,開始寫入檔案到壓縮包中 zipStream.putNextEntry(zipEntry); // 輸入緩衝流 bufferStream = new BufferedInputStream(zipSource, 1024 * 10); int read = 0; // 建立讀寫緩衝區 byte[] buf = new byte[1024 * 10]; while ((read = bufferStream.read(buf, 0, 1024 * 10)) != -1) { zipStream.write(buf, 0, read); } } } catch (Exception e) { e.printStackTrace(); } finally { // 關閉流 try { if (null != bufferStream) bufferStream.close(); if (null != zipStream) zipStream.close(); if (null != zipSource) zipSource.close(); } catch (IOException e) { e.printStackTrace(); } } }
}