java, 批量下载
时间: 2023-10-11 13:14:32 浏览: 30
Java可以使用多种方法实现批量下载文件。其中一种方法是使用Java的URL类和URLConnection类来实现。首先,你需要获取要下载的文件的URL地址列表。然后,对于每个URL,你可以使用URLConnection类打开连接,并使用其getInputStream()方法获取文件的输入流。接下来,你可以使用Java的IO类将文件保存到本地磁盘上。
以下是一个简单的示例代码,演示了如何使用Java实现批量下载文件:
```java
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class FileDownloader {
public static void main(String[] args) {
String[] fileUrls = { "http://example.com/file1.txt", "http://example.com/file2.txt", "http://example.com/file3.txt" };
String saveDir = "C:/downloads/";
try {
for (String fileUrl : fileUrls) {
downloadFile(fileUrl, saveDir);
}
System.out.println("文件下载完成!");
} catch (IOException e) {
e.printStackTrace();
}
}
private static void downloadFile(String fileUrl, String saveDir) throws IOException {
URL url = new URL(fileUrl);
URLConnection connection = url.openConnection();
String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
InputStream inputStream = connection.getInputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
FileOutputStream fileOutputStream = new FileOutputStream(saveDir + fileName);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
fileOutputStream.close();
bufferedInputStream.close();
}
}
```
请注意,上述代码假设你已经有了一个包含要下载文件的URL地址列表的字符串数组fileUrls,以及你希望将文件保存到的目标文件夹saveDir。你可以根据实际需求进行相应的修改。