java下载多个文件并打包
时间: 2023-03-30 21:03:38 浏览: 205
Java实现多文件的文件的压缩和下载
4星 · 用户满意度95%
您好,可以使用Java的IO流和ZipOutputStream类来实现下载多个文件并打包的功能。具体实现可以参考以下代码:
```
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class FileDownloader {
public static void main(String[] args) {
String[] urls = {"http://example.com/file1.txt", "http://example.com/file2.txt", "http://example.com/file3.txt"};
String zipFileName = "files.zip";
downloadAndZipFiles(urls, zipFileName);
}
public static void downloadAndZipFiles(String[] urls, String zipFileName) {
try {
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFileName));
byte[] buffer = new byte[1024];
for (String url : urls) {
URLConnection conn = new URL(url).openConnection();
InputStream in = conn.getInputStream();
ZipEntry entry = new ZipEntry(getFileNameFromUrl(url));
zipOut.putNextEntry(entry);
int len;
while ((len = in.read(buffer)) > ) {
zipOut.write(buffer, , len);
}
in.close();
}
zipOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getFileNameFromUrl(String url) {
int index = url.lastIndexOf("/");
return url.substring(index + 1);
}
}
```
以上代码可以从多个URL下载文件,并将它们打包成一个zip文件。
阅读全文