public class Downloader {
  // 添加@Test标记表示该方法是Junit测试方法,可以直接运行该方法
  @Test
  public void download() throws Exception {
    // 设置URL地址和下载后的文件名
    String filename = 'meitu.exe';
    String path = 'http://10.13.20.32:8080/Test/XiuXiu_Green.exe';
    URL url = new URL(path);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(5000);
    conn.setRequestMethod('GET');
    // 获得需要下载的文件长度(大小)
    int filelength = conn.getContentLength();
    System.out.println('要下载的文件长度' + filelength);
    // 生成一个大小相同的本地文件
    RandomAccessFile file = new RandomAccessFile(filename, 'rwd');
    file.setLength(filelength);
    file.close();
    conn.disconnect();
    // 设置有多少条线程下载
    int threadsize = 3;
    // 计算每个线程下载的量
    int threadlength = filelength % 3 == 0 ? filelength / 3 : filelength + 1;
    for (int i = 0; i < threadsize; i++) {
      // 设置每条线程从哪个位置开始下载
      int startposition = i * threadlength;
      // 从文件的什么位置开始写入数据
      RandomAccessFile threadfile = new RandomAccessFile(filename, 'rwd');
      threadfile.seek(startposition);
      // 启动三条线程分别从startposition位置开始下载文件
      new DownLoadThread(i, startposition, threadfile, threadlength, path).start();
    }
    int quit = System.in.read();
    while ('q' != quit) {
      Thread.sleep(2000);
    }
  }

  private class DownLoadThread extends Thread {
    private int threadid;
    private int startposition;
    private RandomAccessFile threadfile;
    private int threadlength;
    private String path;

    public DownLoadThread(int threadid, int startposition,
        RandomAccessFile threadfile, int threadlength, String path) {
      this.threadid = threadid;
      this.startposition = startposition;
      this.threadfile = threadfile;
      this.threadlength = threadlength;
      this.path = path;
    }

    public DownLoadThread() {}

    @Override
    public void run() {
      try {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod('GET');
        // 指定从什么位置开始下载
        conn.setRequestProperty('Range', 'bytes=' + startposition + '-');
        // System.out.println(conn.getResponseCode());
        if (conn.getResponseCode() == 206) {
          InputStream is = conn.getInputStream();
          byte[] buffer = new byte[1024];
          int len = -1;
          int length = 0;
          while (length < threadlength && (len = is.read(buffer)) != -1) {
            threadfile.write(buffer, 0, len);
            // 计算累计下载的长度
            length += len;
          }
          threadfile.close();
          is.close();
          System.out.println('线程' + (threadid + 1) + '已下载完成');
        }
      } catch (Exception ex) { System.out.println('线程' + (threadid + 1) + '下载出错' + ex); }
    }
  }
}

// Android开发如何调用这个内容:在Android开发中,可以通过创建一个新的线程来调用Downloader类的download方法。具体步骤如下:

// 1. 在Android项目中创建一个新的Java类,例如DownloadTask。

// 2. 在DownloadTask类中创建一个新的线程,并在该线程中调用Downloader类的download方法。

```java
public class DownloadTask extends AsyncTask<Void, Void, Void> {

  @Override
  protected Void doInBackground(Void... voids) {
    Downloader downloader = new Downloader();
    try {
      downloader.download();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
}

// 3. 在需要调用下载方法的地方,创建一个DownloadTask对象,并调用execute方法启动下载任务。

DownloadTask downloadTask = new DownloadTask();
downloadTask.execute();

// 这样就可以在Android应用中调用Downloader类的download方法进行下载任务了。注意,下载任务会在后台线程中执行,不会阻塞主线程,以免导致界面卡顿。

Java多线程下载文件示例 - 使用Junit测试和Android调用

原文地址: https://www.cveoy.top/t/topic/bUWg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录