zip解壓和壓縮
引言
-
介紹zip文件的概念
-
涉及到的Java類和包:
java.util.zip
-
https://blog.csdn.net/u012998680/article/details/126060855
壓縮文件
-
準(zhǔn)備壓縮的源文件和目標(biāo)zip文件的路徑
-
創(chuàng)建
FileOutputStream
和ZipOutputStream
對(duì)象 -
創(chuàng)建源文件的
File
和FileInputStream
對(duì)象 -
創(chuàng)建
ZipEntry
對(duì)象,并設(shè)置其名稱為源文件的名稱 -
使用
ZipOutputStream
的putNextEntry
方法將ZipEntry
對(duì)象添加到壓縮文件中 -
使用循環(huán)讀取源文件的內(nèi)容,并使用
ZipOutputStream
的write
方法將內(nèi)容寫入壓縮文件中 -
關(guān)閉流對(duì)象
解壓縮文件
-
準(zhǔn)備解壓縮的zip文件路徑和目標(biāo)目錄路徑
-
創(chuàng)建目標(biāo)目錄的
File
對(duì)象,如果目錄不存在則創(chuàng)建目錄 -
創(chuàng)建
ZipInputStream
對(duì)象,使用FileInputStream
和zip文件路徑作為參數(shù) -
使用
ZipInputStream
的getNextEntry
方法獲取zip文件的每個(gè)條目ZipEntry
-
循環(huán)處理每個(gè)zip條目,獲取條目的名稱和文件內(nèi)容,并將內(nèi)容寫入目標(biāo)目錄
-
關(guān)閉流對(duì)象
-
示例代碼文章來源:http://www.zghlxwxcb.cn/news/detail-511002.html
創(chuàng)建zip工具類:文章來源地址http://www.zghlxwxcb.cn/news/detail-511002.html
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
?
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
?
?
public class ZipUtil {
? ?// 解壓并返回的key是全路徑
? ?public static Map<String, List<MultipartFile>> unzipAndConvertToMap(File file) throws IOException {
? ? ? ?Map<String, List<MultipartFile>> map = new HashMap<>(); // 存放解壓后的圖片
? ? ? ?byte[] buffer = new byte[1024];
? ? ? ?ZipInputStream zis = new ZipInputStream(new FileInputStream(file),Charset.forName("GBK"));
? ? ? ?try {
? ? ? ? ? ?ZipEntry entry;
? ? ? ? ? ?while ((entry = zis.getNextEntry()) != null) {
?
? ? ? ? ? ? ? ?if (!entry.isDirectory() && isImage(entry.getName())) { // 判斷當(dāng)前解壓的是否是圖片
? ? ? ? ? ? ? ? ? ?// 獲取到全路徑名稱
? ? ? ? ? ? ? ? ? ?String allFileName = entry.getName();
? ? ? ? ? ? ? ? ? ?String[] split = allFileName.split("/");
? ? ? ? ? ? ? ? ? ?// // 圖片名稱
? ? ? ? ? ? ? ? ? ?// String imageName = split[split.length - 1];
? ? ? ? ? ? ? ? ? ?// // 第一層文件夾名稱
? ? ? ? ? ? ? ? ? ?// String firstFile = split[0];
? ? ? ? ? ? ? ? ? ?StringBuffer sb = new StringBuffer();
? ? ? ? ? ? ? ? ? ?for (int i = 1; i < split.length-1; i++) {
? ? ? ? ? ? ? ? ? ? ? ?sb.append(split[i]).append("/");
? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ?String folderName = sb.toString();
? ? ? ? ? ? ? ? ? ?List<MultipartFile> imgList = map.getOrDefault(folderName, new ArrayList<>());
? ? ? ? ? ? ? ? ? ?ByteArrayOutputStream baos = new ByteArrayOutputStream();
? ? ? ? ? ? ? ? ? ?int len;
? ? ? ? ? ? ? ? ? ?while ((len = zis.read(buffer)) > 0) {
? ? ? ? ? ? ? ? ? ? ? ?baos.write(buffer, 0, len);
? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ?MultipartFile multipartFile = new MockMultipartFile(entry.getName(), entry.getName(), "", baos.toByteArray());
? ? ? ? ? ? ? ? ? ?imgList.add(multipartFile);
? ? ? ? ? ? ? ? ? ?map.put(folderName,
到了這里,關(guān)于zip解壓和壓縮的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!