public static void main(String[] args) throws IOException {
DataOutputStream os = null;
ZipOutputStream zipOs = null;
List<String> fileUrls = Arrays.asList("D:\\test\\test1.txt", "D:\\test\\\\test.txt");
try {
File outFile = new File("D:\\test\\zzz.zip");
FileOutputStream fos = new FileOutputStream(outFile);
zipOs = new ZipOutputStream(new BufferedOutputStream(fos));
//设置压缩方法
zipOs.setMethod(ZipOutputStream.DEFLATED);
//遍历文件信息(主要获取文件名/文件路径等)
for (String t : fileUrls) {
File file = new File(t);
FileInputStream fis = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
fis = new FileInputStream(file);
byte[] b = new byte[1000];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
byte[] data = bos.toByteArray();
//文件名(包含后缀名,如:测试.pdf)
String name = t;
log.info("batchDownloadFile:[fileName:{}]", name);
//添加ZipEntry,并将ZipEntry中写入文件流
zipOs.putNextEntry(new ZipEntry(name));
//读入需要下载的文件的内容,打包到zip文件
os = new DataOutputStream(zipOs);
os.write(data);
//关闭流
zipOs.closeEntry();
}
outFile.createNewFile();
} catch (Exception e) {
} finally {
try {
if (os != null) {
os.flush();
os.close();
}
if (zipOs != null) {
zipOs.close();
}
} catch (IOException e) {
log.error("流关闭异常{}", e);
}
}
}
批量下载文件
最新推荐文章于 2024-07-08 15:39:07 发布