package com.soft.zip;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class CreateZip {
public static void main(String[] args) throws IOException {
List<File> list = new ArrayList<File>();
list.add(new File("F:\\報告模板1-監督抽檢.doc"));
list.add(new File("F:\\報告模板2-一般風險監測.doc"));
getZipFile(list);
}
/**
*
* @param fileList 文件集合
* @param zipFileName 壓縮包的名稱
* @return
* @throws IOException
*/
public static File getZipFile(List<File> fileList) throws IOException {
File zipFile = getFile("F:\\", UUID.randomUUID().toString() + ".zip");
// 文件輸出流
FileOutputStream outputStream = new FileOutputStream(zipFile);
// 壓縮流
ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
// zipOutputStream.setEncoding(System.getProperty("UTF-8"));
int size = fileList.size();
// 壓縮列表中的文件
for (int i = 0;i < size;i++) {
File file = fileList.get(i);
zipFile(file, zipOutputStream);
}
// 關閉壓縮流、文件流
zipOutputStream.close();
outputStream.close();
System.err.println("完成");
System.err.println(zipFile.getPath());
return zipFile;
}
/**
* 通過指定路徑和文件名來獲取文件對象,當文件不存在時自動創建
* @param path
* @param fileName
* @return
* @throws IOException
*/
public static File getFile(String path, String fileName) throws IOException {
// 創建文件對象
File file;
if (path != null && !path.equals(""))
file = new File(path, fileName);
else
file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
}
// 返回文件
return file;
}
/**
* 將文件數據寫入文件壓縮流
* @param file 帶壓縮文件
* @param zipOutputStream 壓縮文件流
* @throws IOException
*/
private static void zipFile(File file, ZipOutputStream zipOutputStream) throws IOException {
if (file.exists()) {
if (file.isFile()) {
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
ZipEntry entry = new ZipEntry(file.getName());
zipOutputStream.putNextEntry(entry);
final int MAX_BYTE = 1024 * 1024 * 1024; // 最大流爲10MB
long streamTotal = 0; // 接收流的容量
int streamNum = 0; // 需要分開的流數目
int leaveByte = 0; // 文件剩下的字符數
byte[] buffer; // byte數據接受文件的數據
streamTotal = bis.available(); // 獲取流的最大字符數
streamNum = (int) Math.floor(streamTotal / MAX_BYTE);
leaveByte = (int) (streamTotal % MAX_BYTE);
if (streamNum > 0) {
for (int i = 0;i < streamNum;i++) {
buffer = new byte[MAX_BYTE];
bis.read(buffer, 0, MAX_BYTE);
zipOutputStream.write(buffer, 0, MAX_BYTE);
}
}
// 寫入剩下的流數據
buffer = new byte[leaveByte];
bis.read(buffer, 0, leaveByte); // 讀入流
zipOutputStream.write(buffer, 0, leaveByte); // 寫入流
zipOutputStream.closeEntry(); // 關閉當前的zip entry
// 關閉輸入流
bis.close();
fis.close();
}
}
}
}