Java java下载文件

java下载文件到本地的方法是什么

小亿
219
2023-07-05 00:11:29
栏目: 编程语言

在Java中,可以使用以下方法将文件从网络下载到本地:

  1. 使用Java标准库中的URL类和URLConnection类:
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 fileUrl = "http://example.com/file.txt";
String savePath = "C:/path/to/save/file.txt";
try {
URL url = new URL(fileUrl);
URLConnection connection = url.openConnection();
// 获取文件大小
int fileSize = connection.getContentLength();
// 创建输入流
InputStream inputStream = new BufferedInputStream(url.openStream());
// 创建输出流
FileOutputStream outputStream = new FileOutputStream(savePath);
byte[] buffer = new byte[1024];
int bytesRead;
int downloadedSize = 0;
// 逐个字节读取并写入文件
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
downloadedSize += bytesRead;
System.out.println("下载进度:" + (downloadedSize * 100 / fileSize) + "%");
}
// 关闭流
outputStream.close();
inputStream.close();
System.out.println("文件下载完成!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
  1. 使用第三方库Apache HttpClient:
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileDownloader {
public static void main(String[] args) {
String fileUrl = "http://example.com/file.txt";
String savePath = "C:/path/to/save/file.txt";
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(fileUrl);
// 发送请求并获取响应
CloseableHttpResponse response = httpClient.execute(httpGet);
// 读取响应内容
byte[] fileData = EntityUtils.toByteArray(response.getEntity());
// 将文件内容写入本地文件
FileOutputStream outputStream = new FileOutputStream(savePath);
outputStream.write(fileData);
// 关闭流
outputStream.close();
response.close();
httpClient.close();
System.out.println("文件下载完成!");
} catch (IOException e) {
e.printStackTrace();
}
}
}

无论使用哪种方法,都需要提供文件的URL和要保存到的本地路径。这些示例中使用的是文本文件,但同样适用于其他类型的文件。

0
看了该问题的人还看了