利用URL下载

来源:互联网 发布:数据库第五版答案 编辑:程序博客网 时间:2024/06/11 03:00
利用URL下载
package httpdown.org.jasen;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class DownloadTest {
    publicstatic void main(String[] args) {
       try {
           File file = new File("test.apk");
           HttpURLConnection connection = (HttpURLConnection) newURL("http://skycnxz2.wy119.com/4/wandoujia.apk.apk").openConnection();
           connection.setRequestMethod("GET");
           long sum = 0 ;
           if(file.exists()){
               sum = file.length();
               connection.setRequestProperty("Range","bytes="+file.length()+"-");
           }
           int code = connection.getResponseCode();
           int contentLength = connection.getContentLength();
           contentLength += sum;
           if (code == 200 || code == 206) {
               InputStream is = connection.getInputStream();
               FileOutputStream fos = new FileOutputStream(file, true);
               byte[] buffer = new byte[102400];
               int length = 0 ;
               long startTime = System.currentTimeMillis();
               while ((length = is.read(buffer)) != -1) {
                   fos.write(buffer,0,length);
                   sum += length;
                   float percent = sum * 100.0f/ contentLength;
                   System.out.print("\r[");
                   int p = (int)percent / 2;
                   for (int i = 0; i < 50 ; i++) {
                       if(i < p){
                           System.out.print('=');
                       }else if (i == p){
                           System.out.print('>');
                       }else{
                           System.out.print(' ');
                       }
                   }
                   System.out.print(']');
                   System.out.printf("\t%.2f%%",percent);
                   long value =System.currentTimeMillis()-startTime;
                   long speed = sum * 1000/value;;
                   if(speed > (1 << 20)){
                       System.out.printf("\t%d MB/s",speed >> 20);
                   }else if(speed > (1 << 10)){
                       System.out.printf("\t%d kb/s",speed >> 10);
                   }else {
                       System.out.printf("\t%d b/s",speed);
                   }
               }
           }
       } catch (MalformedURLException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       }
    }
}

0 0