Java如何實(shí)現(xiàn)壓縮文件與解壓縮zip文件
Java壓縮文件與解壓縮zip文件
在日常的使用中經(jīng)常會使用到像WinRAR或WinZIP這樣的壓縮文件,通過這些軟件可以把一個(gè)很大的文件進(jìn)行壓縮以方便傳輸。
在JAVA中 為了減少傳輸時(shí)的數(shù)據(jù)量也提供了專門的壓縮流,可以將文件或文件夾壓縮成ZIP、JAR、GZIP等文件的格式。
ZIP是一種較為常見的壓縮形式,在Java中要想實(shí)現(xiàn)ZIP的壓縮需要導(dǎo)入java.util.zip包,可以使用此包中的ZipFile、ZipOutputStream、ZipInputStream、ZipEntry幾個(gè)類完成。
testZip
package com.kuang.zip; import org.apache.commons.io.IOUtils; import java.io.*; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public class testZip { public static void unZipIt(String file, String outputFolder) throws IOException { ZipFile zipFile = null; InputStream in=null; OutputStream out=null; try { zipFile = new ZipFile(file); Enumeration <? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); File entryDestination = new File(outputFolder, entry.getName()); if (entry.isDirectory()) { entryDestination.mkdirs(); } else { entryDestination.getParentFile().mkdirs(); try { out = new FileOutputStream(entryDestination); in = zipFile.getInputStream(entry); IOUtils.copy(in, out); } catch (IOException e) { throw e; }finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } } } finally { try { if(zipFile!=null){zipFile.close();zipFile=null;} } catch (IOException e) { } } } public static void main(String[] args) throws Exception { unZipIt("D:\\Test\\TestbyYTT.zip","D:\\Test\\"); } }
org.apache.commons.io.IOUtils需引入maven依賴
<!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency>
org.apache.commons.io.IOUtils.closeQuietly()只是確保流會被關(guān)閉,無論流是否正常結(jié)束,看源碼發(fā)現(xiàn)closeQuietly它會忽略異常
那么為什么IOUtils.closeQuietly()會在2.6的時(shí)候?qū)⑺鼧?biāo)記為過時(shí)呢?
因?yàn)镴ava7里的try-with-resource
語法糖的出現(xiàn),之前定義在try catch外部的流移到了try后邊的括號里,不再需要手動關(guān)閉了,它會自行處理。
public static void readAll() { try ( FileReader fileReader = new FileReader("test"); BufferedReader bufferedReader = new BufferedReader(fileReader) ) { String line; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } }
拓展:還有一種語法叫multi-catch
可以簡化多個(gè)catch
FileZip
package com.kuang.zip; import java.io.*; import java.util.zip.*; import java.util.zip.ZipEntry; public class FileZip { /** * zip文件壓縮 * @param inputFile 待壓縮文件夾/文件名 * @param outputFile 生成的壓縮包名字 */ public static void ZipCompress(String inputFile, String outputFile) throws Exception { //創(chuàng)建zip輸出流 ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputFile)); //創(chuàng)建緩沖輸出流 BufferedOutputStream bos = new BufferedOutputStream(out); File input = new File(inputFile); compress(out, bos, input,null); bos.close(); out.close(); } /** * @param name 壓縮文件名,可以寫為null保持默認(rèn) */ //遞歸壓縮 public static void compress(ZipOutputStream out, BufferedOutputStream bos, File input, String name) throws IOException { if (name == null) { name = input.getName(); } //如果路徑為目錄(文件夾) if (input.isDirectory()) { //取出文件夾中的文件(或子文件夾) File[] flist = input.listFiles(); if (flist.length == 0)//如果文件夾為空,則只需在目的地zip文件中寫入一個(gè)目錄進(jìn)入 { out.putNextEntry(new ZipEntry(name + "/")); } else//如果文件夾不為空,則遞歸調(diào)用compress,文件夾中的每一個(gè)文件(或文件夾)進(jìn)行壓縮 { for (int i = 0; i < flist.length; i++) { compress(out, bos, flist[i], name + "/" + flist[i].getName()); } } } else//如果不是目錄(文件夾),即為文件,則先寫入目錄進(jìn)入點(diǎn),之后將文件寫入zip文件中 { out.putNextEntry(new ZipEntry(name)); FileInputStream fos = new FileInputStream(input); BufferedInputStream bis = new BufferedInputStream(fos); int len=-1; //將源文件寫入到zip文件中 byte[] buf = new byte[1024]; while ((len = bis.read(buf)) != -1) { bos.write(buf,0,len); } bis.close(); fos.close(); } } /** * zip解壓 * @param inputFile 待解壓文件名 * @param destDirPath 解壓路徑 */ public static void ZipUncompress(String inputFile,String destDirPath) throws Exception { File srcFile = new File(inputFile);//獲取當(dāng)前壓縮文件 // 判斷源文件是否存在 if (!srcFile.exists()) { throw new Exception(srcFile.getPath() + "所指文件不存在"); } //開始解壓 //構(gòu)建解壓輸入流 ZipInputStream zIn = new ZipInputStream(new FileInputStream(srcFile)); ZipEntry entry = null; File file = null; while ((entry = zIn.getNextEntry()) != null) { if (!entry.isDirectory()) { file = new File(destDirPath, entry.getName()); if (!file.exists()) { new File(file.getParent()).mkdirs();//創(chuàng)建此文件的上級目錄 } OutputStream out = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(out); int len = -1; byte[] buf = new byte[1024]; while ((len = zIn.read(buf)) != -1) { bos.write(buf, 0, len); } // 關(guān)流順序,先打開的后關(guān)閉 bos.close(); out.close(); } } } public static void main(String[] args) { try { ZipCompress("D:\\Test", "D:\\Test\\TestbyYTT.zip"); ZipUncompress("D:\\Test\\TestbyYTT.zip","D:\\Test\\TestbyYTT的解壓文件"); } catch (Exception e) { e.printStackTrace(); } } }
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
UniApp?+?SpringBoot?實(shí)現(xiàn)支付寶支付和退款功能
這篇文章主要介紹了UniApp?+?SpringBoot?實(shí)現(xiàn)支付寶支付和退款功能,基本的?SpringBoot?的腳手架,可以去IDEA?自帶的快速生成腳手架插件,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧2022-06-06關(guān)于Spring?Cache?緩存攔截器(?CacheInterceptor)
這篇文章主要介紹了關(guān)于Spring?Cache緩存攔截器(?CacheInterceptor),具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12Spring security如何重寫Filter實(shí)現(xiàn)json登錄
這篇文章主要介紹了Spring security 如何重寫Filter實(shí)現(xiàn)json登錄,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09詳解多云架構(gòu)下的JAVA微服務(wù)技術(shù)解析
本文介紹了基于開源自建和適配云廠商開發(fā)框架兩種構(gòu)建多云架構(gòu)的思路,以及這些思路的優(yōu)缺點(diǎn)2021-05-05關(guān)于Object中equals方法和hashCode方法判斷的分析
今天小編就為大家分享一篇關(guān)于關(guān)于Object中equals方法和hashCode方法判斷的分析,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-01-01Java實(shí)現(xiàn)Map遍歷key-value的四種方法
本文主要介紹了Java實(shí)現(xiàn)Map遍歷key-value的四種方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07Java java.lang.ExceptionInInitializerError 錯(cuò)誤如何解決
這篇文章主要介紹了 Java java.lang.ExceptionInInitializerError 錯(cuò)誤如何解決的相關(guān)資料,需要的朋友可以參考下2017-06-06