java中wget下载
时间: 2025-01-16 14:55:19 浏览: 47
### 实现 Java 中的 wget 功能
为了在 Java 中实现类似于 `wget` 的文件下载功能,可以使用 `HttpURLConnection` 类来处理 HTTP 请求并保存响应的内容到本地文件。下面是一个完整的解决方案:
#### 使用 HttpURLConnection 下载文件
```java
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class WgetExample {
public static void downloadFile(String fileURL, String saveDir) throws IOException {
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// Check if the request was successful
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpConn.getInputStream();
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
if (disposition != null) {
// Extract filename from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// Extract filename from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
// Save to local directory
OutputStream outputStream = new FileOutputStream(saveDir + File.separator + fileName);
int bytesRead = -1;
byte[] buffer = new byte[4096];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("Downloaded file: " + fileName);
} else {
System.out.println("No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();
}
public static void main(String[] args) {
try {
String fileUrl = "http://example.com/file.zip"; // Replace with your actual URL here.
String dirToSave = "/path/to/save/directory";
downloadFile(fileUrl, dirToSave);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这段代码展示了如何创建一个简单的命令行工具,在给定远程资源的位置时能够自动将其存储到指定位置[^1]。
对于更复杂的需求,比如支持断点续传、多线程下载等功能,则可能需要引入第三方库如 Apache HttpClient 或 OkHttp 来简化开发过程[^2]。
阅读全文
相关推荐

















