对于一些网页内容的需求,我们平时都会有下载的习惯。在位置上一般是存在本地更为安全,常规的保存网页会有一定的丢失风险。除了使用一般的下载方法,学习java后也可以实现视频的下载方法,这里有servlet和common-io的这两种方法供我们挑选,下面我们带来详解的方法介绍。
1.加载servlet容器
不能使用main方法直接调用
publicstaticbooleanhttpDownload(StringhttpUrl,StringsaveFile){
//1.下载网络文件
intbyteRead;
URLurl;
try{
url=newURL(httpUrl);
}catch(MalformedURLExceptione1){
e1.printStackTrace();
returnfalse;
}
try{
//2.获取链接
URLConnectionconn=url.openConnection();
//3.输入流
InputStreaminStream=conn.getInputStream();
//3.写入文件
FileOutputStreamfs=newFileOutputStream(saveFile);
byte[]buffer=newbyte[1024];
while((byteRead=inStream.read(buffer))!=-1){
fs.write(buffer,0,byteRead);
}
inStream.close();
fs.close();
returntrue;
}catch(FileNotFoundExceptione){
e.printStackTrace();
returnfalse;
}catch(IOExceptione){
e.printStackTrace();
returnfalse;
}
}
@Test
publicvoidhttpDownload(){
httpDownload("http://video.zhihuishu.com/zhs/ablecommons/demo/201806/dddee1c446314b84a26c74a8def3c3c7.mp4","E:\\test/22.mp4");
}
2.添加common-io依赖
importorg.apache.commons.io.FileUtils;
importjava.io.File;
importjava.net.URL;
publicclassTestDownloadFile{
publicstaticvoidmain(String[]args)throwsException{
StringurlStr="https://img2018.cnblogs.com/i-beta/1278703/201911/1278703-20191128121650595-812419505.png";
URLurl=newURL(urlStr);
StringtempFileName="E://a.png";
Filetemp=newFile(tempFileName);
FileUtils.copyURLToFile(url,temp);
}
}
原文来自:https://www.py.cn
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END

















































暂无评论内容