public void pack(List httpUrls) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zipout = new ZipOutputStream(bos);
int fileNum = 0;
try {
//排除相同的文件,一个压缩包里面不允许存在相同的文件
Set existFiles = Sets.newHashSet();
for (String httpUrl : httpUrls) {
//从服务器下载文件,获取文件输入流
URL url = new URL(httpUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setConnectTimeout(10 * 1000);
InputStream inputStream = con.getInputStream();
if (Objects.nonNull(inputStream)) {
byte[] buf = new byte[1024];
//这里new ZipEntry最好写文件名,但是我就直接写了httpUrl
zipout.putNextEntry(new ZipEntry(httpUrl));
int len;
while ((len = inputStream.read(buf)) > 0) {
zipout.write(buf, 0, len);
}
zipout.closeEntry();
inputStream.close();
fileNum++;
}
}
} catch (Exception e) {
System.out.println("error:");
} finally {
zipout.close();
bos.close();
}
//上面已经将远程文件全部拉取下来,并且打包压缩完成了,现在压缩的文件数据都在 bos 这个输出流里面了,可以调用本地的方法直接上传到自己的服务器了
//比如我的代码
// String ossUrl = OssService.partUploadLocalFile(ossFileName,bos.toByteArray());
}