命令行多线程下载源代码共享(java)

本文介绍了一个使用Java实现的多线程下载器程序,该程序支持HTTP协议,并通过10个线程并行下载来提高下载速度。文章提供了完整的源代码示例,包括如何划分文件块进行并发下载及进度监控。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
 *该程序采用10线程控制下载,速度大大提升
 *目前支持http协议下载
 *切换到文件所在目录中
 *在命令行中输入java Download5 http://...,回车,即可运行程序
 */

import java.io.*;
import java.net.*;
public class Download5 extends Thread
{
 private long start;
 private long end;
 private String urls,name;
 private int ID;
 public Download5(String urls,String name,int ID,long start,long end)
 {
  this.start=start;
  this.end=end;
  this.urls=urls;
  this.ID=ID;
  this.name=name;
 }
 public void run()
 {
  try
  {
   System.out.println("线程"+ID+"启动...");
   File file=new File(name);
   URL url=new URL(urls);
   URLConnection con=url.openConnection();
   con.setAllowUserInteraction(true);
   con.setRequestProperty("Range","bytes="+start+"-"+end);
   RandomAccessFile rand=new RandomAccessFile(file,"rw");
   rand.seek(start);
   byte[] b=new byte[2048];
   BufferedInputStream buffer=new BufferedInputStream(con.getInputStream());
   int n=0;
   while((n=buffer.read(b,0,b.length))!=-1)
   {
    rand.write(b,0,n);
   }
   System.out.println("线程"+ID+"下载完毕");
   buffer.close();
   rand.close();
   this.interrupt();
  }
  catch(Exception ee)
  {
   ee.printStackTrace();
  }
 }
 public static void main(String[] args)
 {
  String urls=args[0];
  int u=urls.lastIndexOf('/');
  String name=urls.substring(u+1,urls.length());
  try
  {
   long time=System.currentTimeMillis()/1000;
   URL url=new URL(urls);
   URLConnection con=url.openConnection();
   int filelength=con.getContentLength();
   int num=10;
   int size=filelength/num;
   Download5 t=null;
   CountTime count=new CountTime(urls,name,time);
   count.start();
   for(int i=0;i<num;i++)
   {
    if(i!=num-1)
    {
     t=new Download5(urls,name,i+1,size*i,size*(i+1)-1);
     t.start();
    }
    else
    {
     t=new Download5(urls,name,i+1,size*i,filelength);
     t.start();
    }
   }
  }
  catch(Exception ee)
  {
   ee.printStackTrace();
  }
 }
}
class CountTime extends Thread
{
 private String urls,name;
 private long time;
 public CountTime(String urls,String name,long time)
 {
  this.urls=urls;
  this.name=name;
  this.time=time;
 }
 public void run()
 {
  try
  {
   URL url=new URL(urls);
   URLConnection con=url.openConnection();
   int filelength=con.getContentLength();
   File f=new File(name);
   while(f.length()<filelength)
   {
    long LEN=f.length();
    this.sleep(1000);
    System.out.println((f.length()-LEN)/1024/1.0+"kb/s");
   }
   System.out.println("文件下载完毕");
   System.out.println("下载所用总时间: "+(System.currentTimeMillis()/1000-time)+"s");
   this.interrupt();
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值