java多线程下载

来源:互联网 发布:netflix知乎 编辑:程序博客网 时间:2024/06/05 01:08

/*
  * java 多线程下载
  */

package com.wangweijun.downloadersercie;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.os.Environment;
import android.util.Log;
public class MulThreadDownloaderService {
 /*
  * urlStr 资源地址
  */
 public void mulThreadDownloader(String urlStr) throws Exception{
  URL url = new URL(urlStr);
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  conn.setRequestMethod("GET");
  
  // 由链接对象来获取文件大小
  int fileSize = conn.getContentLength();
  conn.disconnect();

  //File file = new File("wang.mp3");
  //本来还要帮段Sdcard 的状态
  File file = new File(Environment.getExternalStorageDirectory(), "wang.mp3");
  // 创建本地随机访问文件,
  RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
  randomAccessFile.setLength(fileSize);
  randomAccessFile.close();

  //线程数目
  int threadNum = 3;
  int threadFileSize = fileSize / threadNum + 1;
  for (int i = 0; i < threadNum; i++) {
   RandomAccessFile threadFile = new RandomAccessFile(file, "rw");
   
   // 设置本地文件开始写入位置
   int startPosition = i * threadFileSize;
   //RandomAccessFile 这个类的好处就是可以设置file 的切点
   //就是说你可以在任意位置读取或写入 data
   threadFile.seek(startPosition);
   
   ThreadLoader tl = new ThreadLoader(url, startPosition, threadFile, threadFileSize, i+1);
   tl.start();

  }
 }
 
 private class ThreadLoader extends Thread{
  private int startPosition;
  private RandomAccessFile threadFile;
  private int threadFileSize;
  private int threadId;
  private URL url;

  public ThreadLoader(URL url , int startPosition,
    RandomAccessFile threadFile, int threadFileSize, int threadId) {
   this.startPosition = startPosition;
   this.threadFile = threadFile;
   this.threadFileSize = threadFileSize;
   this.threadId = threadId;
   this.url = url;
  }

  @Override
  public void run() {
   try {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    // 设置远程文件的开始读入文件
    conn.setRequestProperty("Range", "bytes=" + startPosition + "-");
    
    InputStream inputStream = conn.getInputStream();
    byte buffer[] = new byte[1024];
    int location = -1;
    int totalSize = 0;
    
    while(totalSize <threadFileSize && (location = inputStream.read(buffer)) != -1){
     threadFile.write(buffer, 0, location);
     
     totalSize = totalSize + location;
    }
    threadFile.close();
    inputStream.close();
    conn.disconnect();
    Log.i("ThreadLoader", threadId +" 线程下载完毕");
   } catch (MalformedURLException e) {
    e.printStackTrace();
    System.out.println("MalformedURLException()");
   } catch (IOException e) {
    e.printStackTrace();
    System.out.println("IOException()");
   }
  }
 }
}

源码参考传智播客黎活明老师的3g视频

 

原创粉丝点击