package com.util;java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;apache
/**
* 文件打包
* @author lanxum
*
*/
public class CompressFile {.net
/**
* 壓縮文件
*
* @param srcfile
* File[] 須要壓縮的文件列表
* @param zipfile
* File 壓縮後的文件
*/
public static void zipFiles(java.io.File[] srcfile, java.io.File zipfile) {
byte[] buf = new byte[1024];
try {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
for (int i = 0; i < srcfile.length; i++) {
FileInputStream in = new FileInputStream(srcfile[i]);
out.putNextEntry(new ZipEntry(srcfile[i].getName()));
String str = srcfile[i].getName();
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
in.close();
}
out.close();
System.out.println("壓縮完成.");
} catch (IOException e) {
e.printStackTrace();
}
}ip
/**
* zip解壓縮
*
* @param zipfile
* File 須要解壓縮的文件
* @param descDir
* String 解壓後的目標目錄
*/
public static void unZipFiles(java.io.File zipfile, String descDir) {
try {
ZipFile zf = new ZipFile(zipfile);
for (Enumeration entries = zf.getEntries(); entries.hasMoreElements();) {
ZipEntry entry = ((ZipEntry) entries.nextElement());
String zipEntryName = entry.getName();
InputStream in = zf.getInputStream(entry);
OutputStream out = new FileOutputStream(descDir + zipEntryName);
byte[] buf1 = new byte[1024];
int len;
while ((len = in.read(buf1)) > 0) {
out.write(buf1, 0, len);
}
in.close();
out.close();
// System.out.println("解壓縮完成.");
}
} catch (IOException e) {
e.printStackTrace();
}
}get
public static void main(String[] args) {
File[] strs = new File[2];
strs[0] = new File("D:/print.docx");
strs[1] = new File("D:/print.docx");
CompressFile.zipFiles(strs, new File("d:/print.zip"));it
}
}
io