1. 生成字节输出流ByteArrayOutputStream:
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
2. 由字节输出流生成zip输出流ZipOutputStream:
ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream);
3. 循环每个文件,将每个文件写入文件输入流中--->从文件输入流中读取文件到字节数组中--->将字节数组中的文件内容写入zip输出流中:
for (String path : paths) {
InputStream bin = new FileInputStream(path);
zipOutputStream.putNextEntry(new ZipEntry(path));
int len;
byte[] b = new byte[1024];
while ((len = bin.read(b)) != -1) {
zou.write(b, 0, len);
}
zipOutputStream.closeEntry();
}
4. 循环结束后,结束向zip输出流写入内容:
zipOutputStream.close();
5. 此时文件内容已经存在于字节数组输出流中,可以从字节数组输出流中得到字节数组进行后续的下载操作等:
downloadZipFile(byteArrayOutputStream.toByteArray());