Beispiel #1
0
  /**
   * 开始下载文件
   *
   * @param listener 监听下载数量的变化,如果不需要了解实时下载的数量,可以设置为null
   * @return 已下载文件大小
   * @throws Exception
   */
  public int download(DownloadProgressListener listener) throws Exception {
    try {
      RandomAccessFile randOut = new RandomAccessFile(this.saveFile, "rw");
      if (this.fileSize > 0) randOut.setLength(this.fileSize);
      randOut.close();
      URL url = new URL(this.downloadUrl);

      if (this.data.size() != this.threads.length) {
        this.data.clear();

        for (int i = 0; i < this.threads.length; i++) {
          this.data.put(i + 1, 0); // 初始化每条线程已经下载的数据长度为0
        }
      }

      for (int i = 0; i < this.threads.length; i++) { // 开启线程进行下载
        int downLength = this.data.get(i + 1);

        if (downLength < this.block && this.downloadSize < this.fileSize) { // 判断线程是否已经完成下载,否则继续下载
          this.threads[i] =
              new DownloadThread(this, url, this.saveFile, this.block, this.data.get(i + 1), i + 1);
          this.threads[i].setPriority(7);
          this.threads[i].start();
        } else {
          this.threads[i] = null;
        }
      }

      this.fileService.save(this.downloadUrl, this.data);
      boolean notFinish = true; // 下载未完成

      while (notFinish) { // 循环判断所有线程是否完成下载
        Thread.sleep(900);
        notFinish = false; // 假定全部线程下载完成

        for (int i = 0; i < this.threads.length; i++) {
          if (this.threads[i] != null && !this.threads[i].isFinish()) { // 如果发现线程未完成下载
            notFinish = true; // 设置标志为下载没有完成

            if (this.threads[i].getDownLength() == -1) { // 如果下载失败,再重新下载
              this.threads[i] =
                  new DownloadThread(
                      this, url, this.saveFile, this.block, this.data.get(i + 1), i + 1);
              this.threads[i].setPriority(7);
              this.threads[i].start();
            }
          }
        }

        if (listener != null) listener.onDownloadSize(this.downloadSize); // 通知目前已经下载完成的数据长度
      }

      fileService.delete(this.downloadUrl);
    } catch (Exception e) {
      print(e.toString());
      throw new Exception("file download fail");
    }
    return this.downloadSize;
  }
 @Override
 public void deleteGeneratedImages(URI uri) throws Exception {
   for (ImageStyle imageStyle : imageStyles.values()) {
     fileService.delete(buildGeneratedImagePath(imageStyle, uri));
   }
 }