java实现http下载文件_java使用http实现文件下载学习示例

package com.hongyuan.test;

import java.i

public class FileDownload {

public static final String LOCAL_PATH="d:/";

public static void main(String[] args) {

//待下载文件地址

String fileUrl="http://211.162.55.16/cdn.baidupcs.com/file/6a73dab7c03023a9835cc737f447674d?xcode=af6ffdc43a44169bac968d32c4bd420084a9a97c308112c9&fid=3255571826-250528-130564002&time=1397293108&sign=FDTAXER-DCb740ccc5511e5e8fedcff06b081203-mQkOeRDtXpyQWwYJkI%2BxKJpxn5k%3D&to=cb&fm=N,B,U,nc&newver=1&expires=1397297563&rt=sh&r=854979042&logid=1751715936&sh=1&vuk=3255571826&fn=Web%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%20%E7%AC%AC5%E7%89%88UzJZdd.pdf&wshc_tag=0&wsiphost=ipdbm";

InputStream in=null;

OutputStream out=null;

&nbsphttp://www.cppcns.com;HttpURLConnection conn=null;

String fileName=null;

try {

//初始化连接

URL url=new URL(fileUrl);

conn = (HttpURLConnection) url.openConnection();

conn.setDoInput(true);

conn.setDoOutput(true);

//获取文件名

String disposition=conn.getHeaderField("Content-Disposition");

if(disposition!=null&&!"".equals(disposition)){

//从头中获取文件名

fileName=disposition.split(";")[1].spli编程客栈t("=")[1].replaceAll("\"","");

}else{

//从地址中获取文件名

fileName=fileUrl.substring(fileUrl.lastIndexOf("/")+1);

}

if(fileName!=null&&!"".equals(fileName)){

//文件名解码

fileName=URLDecoder.decode(fileName, "utf-8");

}else{

//如果无法获取文件名,则随机生成一个

fileName="file_"+(int)(Math.random()*10);

}

//读取数据

if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){

byte[] buffer=new byte[2048];

in = conn.getInputStream();

out=new FileOutputStream(new File(LOCAL_PATH,fileName));

int count=0;

int finished=0;

int size=conn.getContentLength();

while((count=in.read(buffer))!=-1){

if(count!=0){

out.write(buffer,0,count);

finished+=count;

System.out.printf("########################################---->%1$.2f%%\n",(double)finished/size*100);

}else{

break;

}

}

}

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}finally{

try {

out.close();

in.close();

conn.disconnect();

} catch (IOException e) {

e.printStackTrace();

}

www.cppcns.com}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值