java通过url下载文件
通过流的方式进行下载:
代码如下:
/**
* 通过url地址进行下载文件
* @param url 网页地址
* @param fileName 文件名,不包含文件路径需要自己配置
*/
public static void downloadByUrl(String url,String fileName){
BufferedInputStream inputStream=null;
FileOutputStream fileOutputStream=null;
try {
URL path=new URL(url);
inputStream=new BufferedInputStream(path.openStream());
fileOutputStream=new FileOutputStream(fileName);
byte[] bytes=new byte[1024];//1m
int len=0;//为什么需要记录长度,便于在写入的时候确定长度
while ((len=inputStream.read(bytes))!=-1){
fileOutputStream.write(bytes,0,len);//将读取的文件进行写出
}
fileOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
本文作者:just1t
本文链接:https://www.cnblogs.com/just1t/p/17176684.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步