ZIP 是一种存档文件格式,支持无损数据压缩。 一个 ZIP 文件可能包含一个或多个已压缩的文件或目录。 Java Archive(JAR)建立在 ZIP 格式上。
采用ZipOutputStream/ZipInputStream是工具对文件进行压缩和解压
- ZipInputStream是 Java 类,实现用于读取 ZIP 文件格式的文件的输入流过滤器。 它支持压缩和未压缩的条目。
ZipInputStream(InputStream in)
ZipInputStream(InputStream in, Charset charset)
ZipInputStream's getNextEntry()读取下一个 ZIP 文件条目,并将流定位在条目数据的开头。
- ZipOutputStream:完成一个文件或文件夹的压缩,要使用ZipOutputStream类完成,ZipOutputStream是OutputStream的子类
ZipOutputStream(OutputStream out) 构造方法 创建新的ZIP输出流
在压缩文件中,每一个压缩的内容都可以用一个ZipEntry表示,所以在进行压缩之前必须通过putNextEntry设置一个ZipEntry即可。
Java 读取 ZIP 示例
public static Map<String, String> unzip(@RequestParam("file") MultipartFile file) {
// 判断文件是否为zip文件
String filename = file.getOriginalFilename();
if (!filename.endsWith("zip")) {
LOGGER.info("传入文件格式不是zip文件" + filename);
new BusinessException("传入文件格式错误" + filename);
}
Map<String, String> fileContentMap = Maps.newHashMap();
String zipFileName = null;
// 对文件进行解析
try {
ZipInputStream zipInputStream = new ZipInputStream(file.getInputStream(), Charset.forName("GBK"));
BufferedInputStream bs = new BufferedInputStream(zipInputStream);
ZipEntry zipEntry;
byte[] bytes = null;
while ((zipEntry = zipInputStream.getNextEntry()) != null) { // 获取zip包中的每一个zip file entry
zipFileName = zipEntry.getName();
Assert.notNull(zipFileName, "压缩文件中子文件的名字格式不正确");
bytes = new byte[(int) zipEntry.getSize()];
bs.read(bytes, 0, (int) zipEntry.getSize());
fileContentMap.put(zipFileName, new String(bytes));
}
} catch (Exception e) {
LOGGER.error("读取部署包文件内容失败,请确认部署包格式正确:" + zipFileName, e);
new BusinessException("读取部署包文件内容失败,请确认部署包格式正确:" + zipFileName);
}
return fileContentMap;
}
Java 压缩 ZIP 示例
public static void listTozip(List<ZipStreamEntity> listStream, String fileName, HttpServletResponse response) {
ZipOutputStream zos = null;
OutputStream out = null;
try {
out = response.getOutputStream();
response.reset();
response.setHeader("Content-Disposition",
"attachment;filename=" + new String(fileName.getBytes("GB2312"), "ISO-8859-1"));
response.setContentType("application/octet-stream; charset=utf-8");
response.setCharacterEncoding("UTF-8");
zos = new ZipOutputStream(out);
byte[] bufs = new byte[1024 * 10];
for (ZipStreamEntity zipstream : listStream) {
String streamfilename = StringUtils.isnull(zipstream.getName());
// 创建ZIP实体,并添加进压缩包
ZipEntry zipEntry = new ZipEntry(streamfilename);
zos.putNextEntry(zipEntry);
// 读取待压缩的文件并写进压缩包里
BufferedInputStream bis = new BufferedInputStream(zipstream.getInputstream(), 1024 * 10);
int read = 0;
while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
zos.write(bufs, 0, read);
}
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
// 关闭流
try {
if (null != bis)
bis.close();
if (null != zos)
zos.close();
if (null != out)
out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}