Android实现多线程下载文件的方法

2019-12-10 19:58:34王冬梅

下载文件的线程

 

 
  1. public class FileDownloadThread extends Thread{   private static final int BUFFER_SIZE=1024;  
  2. private URL url;   private File file;  
  3. private int startPosition;   private int endPosition;  
  4. private int curPosition;   //标识当前线程是否下载完成  
  5. private boolean finished=false;   private int downloadSize=0;  
  6. public FileDownloadThread(URL url,File file,int startPosition,int endPosition){   this.url=url;  
  7. this.file=file;   this.startPosition=startPosition;  
  8. this.curPosition=startPosition;   this.endPosition=endPosition;  
  9. }   @Override 
  10. public void run() {   BufferedInputStream bis = null;  
  11. RandomAccessFile fos = null;   byte[] buf = new byte[BUFFER_SIZE];  
  12. URLConnection con = null;   try {  
  13. con = url.openConnection();   con.setAllowUserInteraction(true);  
  14. //设置当前线程下载的起止点   con.setRequestProperty("Range", "bytes=" + startPosition + "-" + endPosition);  
  15. Log.i("bb", Thread.currentThread().getName()+" bytes=" + startPosition + "-" + endPosition);   //使用java中的RandomAccessFile 对文件进行随机读写操作  
  16. fos = new RandomAccessFile(file, "rw");   //设置写文件的起始位置  
  17. fos.seek(startPosition);   bis = new BufferedInputStream(con.getInputStream());  
  18. //开始循环以流的形式读写文件   while (curPosition < endPosition) {  
  19. int len = bis.read(buf, 0, BUFFER_SIZE);   if (len == -1) {  
  20. break;   }  
  21. fos.write(buf, 0, len);   curPosition = curPosition + len;  
  22. if (curPosition > endPosition) {   downloadSize+=len - (curPosition - endPosition) + 1;