import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class UnzipFileWithChineseName {
public static void main(String[] args) {
MultipartFile zipFile; // 从Spring MultipartFile获取ZIP文件
String targetFolderPath = "/path/to/target/folder"; // 解压后的目标文件夹路径
try (ZipInputStream zipInputStream = new ZipInputStream(zipFile.getInputStream(), StandardCharsets.UTF_8)) {
// 注意一下,zip包的默认读取是GBK,如果报错就是用UTF-8,中文
ZipEntry entry;
while ((entry = zipInputStream.getNextEntry()) != null) {
if (!entry.isDirectory()) {
String entryName = entry.getName();
System.out.println("Extracting: " + entryName);
String targetFilePath = targetFolderPath + File.separator + entryName;
File targetFile = new File(targetFilePath);
// 确保目标文件夹存在
targetFile.getParentFile().mkdirs();
// 写入解压后的文件
try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(targetFile))) {
byte[] buffer = new byte[1024];
int length;
while ((length = zipInputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
}
}
zipInputStream.closeEntry();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
JAVA关于Zip压缩包的处理
最新推荐文章于 2024-06-20 20:20:21 发布