標籤:
[使用java進行壓縮和解壓縮]
親測可用:
import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import java.util.Enumeration;import java.util.zip.ZipEntry;import java.util.zip.ZipFile;import java.util.zip.ZipOutputStream;public class TestZIP {/** * 功能:壓縮多個檔案成一個zip檔案 * @param srcfile:源檔案清單 * @param zipfile:壓縮後的檔案 */public static void zipFiles(File[] srcfile, File zipfile) {byte[] buf = new byte[1024];try {//ZipOutputStream類:完成檔案或檔案夾的壓縮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()));int len;while ((len = in.read(buf)) > 0) {out.write(buf, 0, len);}out.closeEntry();in.close();}out.close();System.out.println("壓縮完成.");} catch (Exception e) {e.printStackTrace();}}/** * 功能:解壓縮 * @param zipfile:需要解壓縮的檔案 * @param descDir:解壓後的目標目錄 */public static void unZipFiles(File zipfile, String descDir) {try {ZipFile zf = new ZipFile(zipfile);for (Enumeration entries = zf.entries(); 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 (Exception e) {e.printStackTrace();}}/**功能: * @param args */public static void main(String[] args) {//2個源檔案File f1 = new File("D:\\test\\1.csv");File f2 = new File("D:\\test\\2.xlsx");File[] srcfile = { f1, f2 };//壓縮後的檔案File zipfile = new File("D:\\test\\3.zip");TestZIP.zipFiles(srcfile, zipfile);//需要解壓縮的檔案File file = new File("D:\\test\\3.zip");//解壓後的目標目錄String dir = "D:\\test\\1\\";TestZIP.unZipFiles(file, dir);}}
JAVA實現多檔案壓縮和解壓縮