在jdk8中,java http下载文件到本地
时间: 2024-01-29 11:29:05 浏览: 138
在JDK 8中,你可以使用Java的标准库中的 HttpURLConnection 类来进行HTTP文件下载。下面是一个简单的示例代码,演示如何使用 HttpURLConnection 下载文件到本地:
```java
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileDownloader {
public static void main(String[] args) {
String fileUrl = "http://example.com/file.pdf";
String savePath = "/path/to/save/file.pdf";
try {
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
FileOutputStream fileOutputStream = new FileOutputStream(savePath);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
fileOutputStream.close();
bufferedInputStream.close();
System.out.println("文件下载完成!");
} else {
System.out.println("文件下载失败。响应代码:" + responseCode);
}
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上面的示例中,你需要将 `fileUrl` 替换为要下载的文件的URL,将 `savePath` 替换为要保存文件的本地路径。运行示例代码后,它将从指定的URL下载文件并将其保存到本地路径中。请确保你有适当的权限来写入指定的文件路径。
阅读全文