Java下载HTTP URL链接示例
这里以下载迅雷U享版为例。
示例代码:
package com.zifeiy.snowflake.handle.filesget;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class HttpFileGetter {
public boolean download(String urlString, File localFile) {
try {
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
connection.setConnectTimeout(5*1000);
InputStream inputStream = connection.getInputStream();
byte[] byteArr = new byte[1024];
int len;
File dir = localFile.getParentFile();
if (dir.exists() == false)
dir.mkdirs();
OutputStream outputStream = new FileOutputStream(localFile);
while ((len = inputStream.read(byteArr)) != -1) {
outputStream.write(byteArr, 0, len);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
// main for test
public static void main(String[] args) {
HttpFileGetter httpFileGetter = new HttpFileGetter();
httpFileGetter.download("http://down.sandai.net/ThunderVIP/ThunderVIP-xlgw.exe", new File("D:\\test_download.exe"));
}
}
下载下来的程序运行也没有问题:
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步