JAVA實現多檔案壓縮和解壓縮

來源:互聯網
上載者:User

標籤:

[使用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實現多檔案壓縮和解壓縮

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.