Download from URL in Java

Description

The following code shows how to download from URL.

Example


   //ww w  .  j  a va2 s .c o m
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

public class Utils {
  public static void download(String urlStr, File destFile) throws IOException {
    URL srcUrl = new URL(urlStr);

    InputStream input = null;
    OutputStream output = null;
    try {
      input = srcUrl.openStream();
      FileOutputStream fos = new FileOutputStream(destFile);
      output = new BufferedOutputStream(fos);
      copyStreams(input, output);
    } finally {
      if (input != null) {
        input.close();
      }
      if (output != null) {
        output.flush();
        output.close();
      }
    }
  }

  private static void copyStreams(InputStream input, OutputStream output) throws IOException {
    int count;
    byte data[] = new byte[1024];
    while ((count = input.read(data, 0, 1024)) != -1) {
      output.write(data, 0, count);
    }
  }
}




















Home »
  Java Tutorial »
    Network »




NetworkInterface
URI
URL
HTTP
HTTP Read
IP
Socket
UDP
URL Encode