断点下载,一个线程

来源:互联网 发布:淘宝店铺看不到宝贝 编辑:程序博客网 时间:2024/04/30 22:46

思想:

     读取没下载完的文件的大小,通知从哪开始下载  con.setRequestProperty("Range","bytes:"+fileSize+"-")

publicvoid down2()throws Exception{

       //先声明要保存的目录

       File file = new File("f:/01.avi");

       //读取文件的大小

       long fileSize = file.length();//读取文件的大小

       //1.声明URL

       URL url = new URL("http://localhost:8080/0515/down/01.avi");

       //2.获取urlconnection

       HttpURLConnection con = (HttpURLConnection)url.openConnection();

       //3.设置请求类型

       con.setRequestMethod("GET");

       //4.设置可以读取服务器的数据

       con.setDoInput(true);

       con.setDoOutput(true);

       //5.设置下载一部分数据

       con.setRequestProperty("Range","bytes:"+fileSize+"-" );//传递从哪儿开始下载

       //6.连接

       con.connect();

       //7.判断连接是否成功

       int code = con.getResponseCode();

       if(code==200||code==206){//判断206.

           //获取服务器的数据是多少

           int contentLength = con.getContentLength();

           //8.读取服务器返回的io

           InputStream in= con.getInputStream();

           OutputStream out = new FileOutputStream(file,true);

           byte[] b =newbyte[1024*256];

           int len = 0;

           int sum = 0;//计算下载的总量

           while((len=in.read(b))!=-1){

              sum+=len;

              System.err.println(sum+"/"+contentLength);

              out.write(b, 0, len);

           }

           out.close();

           in.close();

       }

       con.disconnect();

  }

}