Example #1
0
  /**
   * Simple Download
   *
   * @param url url to download from
   * @param localFile local file name
   * @param blocksize block size to download
   * @param maxCacheAge the max time (in seconds) that proxies should cache things. -1 = forever.
   * @throws IOException for IO error
   */
  public static void download(String url, File localFile, int blocksize, int maxCacheAge)
      throws IOException {
    // FileOutputStream object.
    FileOutputStream fs = null;
    // InputStream.
    InputStream is = null;

    byte[] b = new byte[blocksize];
    int bytesRead;
    boolean finished = false;
    // create our output directories.
    localFile.getParentFile().mkdirs();
    try {
      // open the URL,
      URL endpoint = new URL(url);
      URLConnection connection = endpoint.openConnection();
      if (maxCacheAge >= 0) {
        connection.addRequestProperty(CACHE_CONTROL, Integer.toString(maxCacheAge));
      }
      is = connection.getInputStream();

      // open the file,
      fs = new FileOutputStream(localFile);

      // transfer the data
      do {
        bytesRead = is.read(b, 0, blocksize);
        if (bytesRead > 0) {
          fs.write(b, 0, bytesRead);
        }
      } while (bytesRead > 0);
      // mark as finished
      finished = true;
      fs.close();
    } finally {
      FileSystem.close(fs);
      FileSystem.close(is);
      // delete any half-downloaded local file if
      // something went wrong during download.
      if (!finished && localFile.exists()) {
        localFile.delete();
      }
    }
  }