java如何使用zip壓縮實現(xiàn)讀取寫入
更新時間:2023年11月06日 10:51:12 作者:bug生產(chǎn)者
這篇文章主要為大家介紹了java如何使用zip壓縮實現(xiàn)讀取寫入示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
zip壓縮
zip文檔可以以壓縮格式存儲一個或多個文件,可以使用ZipInputStream讀取Zip文檔,使用ZipOutputStream來寫入到Zip文件中
ZipInputStream讀取
ZipInputStream zin = new ZipInputStream(in); ZipEntry ze; // getNextEntry返回描述這個項的ZipEntry的對象 while ((ze = zin.getNextEntry()) != null) { // getInputStream獲取用于讀取該項的輸入流 BufferedReader br = new BufferedReader( new InputStreamReader(zf.getInputStream(ze), charset)); // 業(yè)務(wù)邏輯 todo br.close(); // closeEntry關(guān)閉當(dāng)前打開的項 zin.closeEntry(); } zin.close();
ZipOutputStream寫入
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile)); File fileWillZip = new File(dir); if (fileWillZip.exists()) { // 需要壓縮的文件是文件夾。需要遞歸進(jìn)行壓縮 if(fileWillZip.isDirectory()){ compressZip(zipOut,fileWillZip,fileWillZip.getName()); } else { // 是文件,直接壓縮 zip(zipOut,fileWillZip,dir); } } zipOut.closeEntry(); zipOut.close(); private void compressZip(ZipOutputStream zipOutput, File file, String suffixpath) { File[] listFiles = file.listFiles();// 列出所有的文件 for(File fi : listFiles){ if(fi.isDirectory()){ // 如果是文件夾,繼續(xù)遞歸 if(suffixpath.equals("")){ compressZip(zipOutput, fi, fi.getName()); }else{ compressZip(zipOutput, fi, suffixpath + File.separator + fi.getName()); } }else{ zip(zipOutput, fi, suffixpath); } } } public void zip(ZipOutputStream zipOutput, File file, String suffixpath) { try { // 創(chuàng)建ZipEntry對象 ZipEntry zEntry = null; if(suffixpath.equals("")){ zEntry = new ZipEntry(file.getName()); }else{ zEntry = new ZipEntry(suffixpath + File.separator + file.getName()); } // putNextEntry將給定的ZipEntry中的信息寫出到輸出流,并定位用于寫出數(shù)據(jù)的流,然后這些數(shù)據(jù)可以通過write方法寫出到這個輸出流中 zipOutput.putNextEntry(zEntry); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); byte[] buffer = new byte[1024]; int read = 0; while((read = bis.read(buffer)) != -1){ zipOutput.write(buffer, 0, read); } bis.close(); } catch (Exception e) { e.printStackTrace(); } }
以上就是java如何使用zip壓縮實現(xiàn)讀取寫入的詳細(xì)內(nèi)容,更多關(guān)于java zip壓縮讀取寫入的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
java 學(xué)習(xí)筆記(入門篇)_多選擇結(jié)構(gòu)switch語句
在java中為多路分支選擇流程專門提供了switch語句,switch語句根據(jù)一個表達(dá)式的值,選擇運行多個操作中的一個,感興趣的朋友可以了解下2013-01-01在SpringBoot當(dāng)中使用Thymeleaf視圖解析器的詳細(xì)教程
Thymeleaf是一款開源的模板引擎,它允許前端開發(fā)者使用HTML與XML編寫動態(tài)網(wǎng)頁,hymeleaf的主要特點是將表達(dá)式語言嵌入到HTML結(jié)構(gòu)中,它支持Spring框架,使得在Spring MVC應(yīng)用中集成非常方便,本文給大家介紹了在SpringBoot當(dāng)中使用Thymeleaf視圖解析器的詳細(xì)教程2024-09-09BufferedReader中read()方法和readLine()方法的使用
這篇文章主要介紹了BufferedReader中read()方法和readLine()方法的使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-04-04Java圖書管理系統(tǒng),課程設(shè)計必用(源碼+文檔)
本系統(tǒng)采用Java,MySQL 作為系統(tǒng)數(shù)據(jù)庫,重點開發(fā)并實現(xiàn)了系統(tǒng)各個核心功能模塊,包括采編模塊、典藏模塊、基礎(chǔ)信息模塊、流通模塊、期刊模塊、查詢模塊、評論模塊、系統(tǒng)統(tǒng)計模塊以及幫助功能模塊2021-06-06