java解析zip文件
1.工具类
package org.springblade.iot.utils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
public class ZipUtil {
public static List<MultipartFile> extractZip(MultipartFile multipartFile) throws IOException {
List<MultipartFile> list = new ArrayList<>();
InputStream input = multipartFile.getInputStream();
ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(input), Charset.forName("GBK"));
ByteArrayOutputStream byteOut = null;
InputStream inputStream = null;
ZipEntry ze = null;
while ((ze = zipInputStream.getNextEntry()) != null) {
byteOut = new ByteArrayOutputStream();
IOUtils.copy(zipInputStream, byteOut);
inputStream = new ByteArrayInputStream(byteOut.toByteArray());
list.add(getMultipartFile(inputStream, ze.getName()));
}
zipInputStream.closeEntry();
input.close();
if (byteOut != null) {
byteOut.close();
}
if (inputStream != null) {
inputStream.close();
}
return list;
}
public static MultipartFile getMultipartFile(InputStream inputStream, String fileName) {
FileItem fileItem = createFileItem(inputStream, fileName);
return new CommonsMultipartFile(fileItem);
}
public static FileItem createFileItem(InputStream inputStream, String fileName) {
FileItemFactory factory = new DiskFileItemFactory(16, null);
String textFieldName = "file";
FileItem item = factory.createItem(textFieldName, MediaType.MULTIPART_FORM_DATA_VALUE, true, fileName);
int bytesRead = 0;
byte[] buffer = new byte[8192];
OutputStream os = null;
try {
os = item.getOutputStream();
while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
inputStream.close();
} catch (IOException e) {
throw new IllegalArgumentException("文件上传失败");
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
}
return item;
}
}