public static void download(String httpUrl,String saveFile){
// 下载网络文件
long bytesum = 0;
int byteread = 0;
long bytetotal = 0;
FileOutputStream fs = null;
URL url = null;
try {
url = new URL(httpUrl);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
try {
int timeout = 30;
URLConnection conn = url.openConnection();
conn.setConnectTimeout(timeout*1000);
conn.setReadTimeout(timeout*1000);
InputStream inStream = conn.getInputStream();
fs = new FileOutputStream(saveFile);
bytetotal = conn.getContentLength();
byte[] buffer = new byte[1024];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
//这里可以计算下载的进度,根据你的需要进行操作
fs.write(buffer, 0, byteread);
}
if(bytesum!=bytetotal){//文件不匹配时,直接返回
//结果不匹配,按照你的需要进行操作
//your code
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(fs!=null){
try{fs.close();fs=null;}catch(Exception e){e.printStackTrace();}
}
}
}文件下载就是将一个url所指向的文件保存到一个文件里面去,但是许多资源分为直链和外链,直链就是直接根据链接就可以下载文件,外链是通过java方法指向某个文件,再将文件以流的形式传到用户。就是说外链可能有许多其他的限制,比如身份验证什么之类的。博主给的例子只针对直链。如果大家要对外链进行下载的话,就必须生成直链再进行下载。
354



被折叠的 条评论
为什么被折叠?



