如何用Java编程实现从指定路径下载ZIP文件并保存到本地
时间: 2024-12-16 19:32:33 浏览: 4
在Java中,你可以使用`java.io`和`java.util.zip`包提供的功能来下载ZIP文件并保存到本地。以下是一个简单的示例,展示了如何使用`HttpURLConnection`从URL下载文件,并将其保存到本地:
```java
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadZipFile {
public static void downloadAndSave(String sourceUrl, String destinationPath) throws IOException {
// 创建URL对象
URL url = new URL(sourceUrl);
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
// 检查是否成功请求
int responseCode = connection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Failed : HTTP error code : " + responseCode);
}
// 获取输入流
InputStream inputStream = connection.getInputStream();
// 创建输出目录,如果不存在的话
File outputDirectory = new File(destinationPath);
if (!outputDirectory.exists()) {
outputDirectory.mkdirs();
}
// 定义文件名
File outputFile = new File(outputDirectory, "downloaded_file.zip");
// 创建输出流
FileOutputStream outputStream = new FileOutputStream(outputFile);
// 将输入流数据写入输出流
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
// 关闭流
outputStream.close();
inputStream.close();
System.out.println("Downloaded file saved to " + outputFile.getAbsolutePath());
}
public static void main(String[] args) {
try {
String sourceUrl = "http://example.com/file.zip"; // 替换为你想要下载的ZIP文件地址
String localPath = "/path/to/save/download"; // 替换为你本地的目标保存路径
downloadAndSave(sourceUrl, localPath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这个示例假设源URL指向的是一个可用的ZIP文件。记得替换`sourceUrl`和`destinationPath`为实际的URL和目标存储位置。运行`main`方法即可开始下载。
阅读全文