Android通過HTTP協議實現多線程下載

jopen 11年前發布 | 31K 次閱讀 Android Android開發 移動開發

import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

public class MulThreadDownload {

/**
 * @param args
 */
public static void main(String[] args) {
    String path = "http://net.itcast.cn/QQWubiSetup.exe";
    try {
        new MulThreadDownload().download(path, 3);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
/**
 * 從路徑中獲取文件名稱
 * @param path 下載路徑
 * @return
 */
public static String getFilename(String path){
    return path.substring(path.lastIndexOf('/')+1);
}
/**
 * 下載文件
 * @param path 下載路徑
 * @param threadsize 線程數
 */
public void download(String path, int threadsize) throws Exception{
    URL url = new URL(path);
    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    conn.setRequestMethod("GET");
    conn.setConnectTimeout(5 * 1000);
    int filelength = conn.getContentLength();//獲取要下載的文件的長度
    String filename = getFilename(path);//從路徑中獲取文件名稱
    File saveFile = new File(filename);
    RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd");
    accessFile.setLength(filelength);//設置本地文件的長度和下載文件相同
    accessFile.close();
    //計算每條線程下載的數據長度
    int block = filelength%threadsize==0? filelength/threadsize : filelength/threadsize+1;
    for(int threadid=0 ; threadid < threadsize ; threadid++){
        new DownloadThread(url, saveFile, block, threadid).start();
    }
}

private final class DownloadThread extends Thread{
    private URL url;
    private File saveFile;
    private int block;//每條線程下載的數據長度
    private int threadid;//線程id

    public DownloadThread(URL url, File saveFile, int block, int threadid) {
        this.url = url;
        this.saveFile = saveFile;
        this.block = block;
        this.threadid = threadid;
    }

    @Override
    public void run() {
        //計算開始位置公式:線程id*每條線程下載的數據長度= ?
        //計算結束位置公式:(線程id +1)*每條線程下載的數據長度-1 =?
        int startposition = threadid * block;
        int endposition = (threadid + 1 ) * block - 1;
        try {
            RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd");
            accessFile.seek(startposition);//設置從什么位置開始寫入數據
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            conn.setRequestProperty("Range", "bytes="+ startposition+ "-"+ endposition);
            InputStream inStream = conn.getInputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while( (len=inStream.read(buffer)) != -1 ){
                accessFile.write(buffer, 0, len);
            }
            inStream.close();
            accessFile.close();
            System.out.println("線程id:"+ threadid+ "下載完成");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }       
}

}</pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!