在Java中通过HTTP网络URL下载文件的方法如下:
import java.io.*;
import java.net.*;
public class FileDownloader {
public static void main(String[] args) {
String fileUrl = "https://example.com/file.txt"; // 文件的URL地址
String savePath = "path/to/save/file.txt"; // 保存文件的本地路径
try {
URL url = new URL(fileUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
// 获取输入流
InputStream inputStream = httpURLConnection.getInputStream();
// 创建输出流
FileOutputStream fileOutputStream = new FileOutputStream(new File(savePath));
// 从输入流读取数据并写入输出流
int bytesRead;
byte[] buffer = new byte[4096];
while ((bytesRead = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
// 关闭流
fileOutputStream.close();
inputStream.close();
System.out.println("文件下载完成。");
} catch (IOException e) {
e.printStackTrace();
}
}
}
将上述代码中的 fileUrl
替换为要下载的文件的URL地址,savePath
替换为要保存文件的本地路径。运行这个Java程序,它将从指定的URL下载文件并保存到本地路径中。
请注意,代码中没有添加错误处理,实际操作中应该添加适当的错误处理以处理网络连接和IO异常。
香港五网CN2网络云服务器链接:www.tsyvps.com
蓝易云香港五网CN2 GIA/GT精品网络服务器。拒绝绕路,拒绝不稳定。