java如何使用zip壓縮實現(xiàn)讀取寫入
更新時間:2023年11月06日 10:51:12 作者:bug生產者
這篇文章主要為大家介紹了java如何使用zip壓縮實現(xià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è)務邏輯 todo
br.close();
// closeEntry關閉當前打開的項
zin.closeEntry();
}
zin.close();ZipOutputStream寫入
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
File fileWillZip = new File(dir);
if (fileWillZip.exists()) {
// 需要壓縮的文件是文件夾。需要遞歸進行壓縮
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ù)據的流,然后這些數(shù)據可以通過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)讀取寫入的詳細內容,更多關于java zip壓縮讀取寫入的資料請關注腳本之家其它相關文章!
相關文章
在SpringBoot當中使用Thymeleaf視圖解析器的詳細教程
Thymeleaf是一款開源的模板引擎,它允許前端開發(fā)者使用HTML與XML編寫動態(tài)網頁,hymeleaf的主要特點是將表達式語言嵌入到HTML結構中,它支持Spring框架,使得在Spring MVC應用中集成非常方便,本文給大家介紹了在SpringBoot當中使用Thymeleaf視圖解析器的詳細教程2024-09-09
BufferedReader中read()方法和readLine()方法的使用
這篇文章主要介紹了BufferedReader中read()方法和readLine()方法的使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-04-04
Java圖書管理系統(tǒng),課程設計必用(源碼+文檔)
本系統(tǒng)采用Java,MySQL 作為系統(tǒng)數(shù)據庫,重點開發(fā)并實現(xiàn)了系統(tǒng)各個核心功能模塊,包括采編模塊、典藏模塊、基礎信息模塊、流通模塊、期刊模塊、查詢模塊、評論模塊、系統(tǒng)統(tǒng)計模塊以及幫助功能模塊2021-06-06

