Storing the contents of a URL to a file

This example shows how to store the contents of a URL to a File.


public class URLFetcher {
  private String urlString;
  private String fileName;
  public URLFetcher(String urlString, String fileName) {
    this.urlString = urlString;
    this.fileName = fileName;

  public void fetch() throws Exception {
    byte buffer[] = new byte[1024]; // change 1024 to better match your needs
    int numRead = 0;
    URL url = new URL(this.urlString);
    OutputStream os = new FileOutputStream(new File(this.fileName));
    InputStream is = url.openStream();
    while ( (numRead =,0,1024)) != -1) {
      os.write(buffer, 0, numRead);

Using the URLFetcher:

URLFetcher urlFetcher = new URLFetcher("myUrl", "myFileName");
try {
} catch(Exception e) {


Note: This article originally appeared in my Java blog (  I’m shutting that one down, so I’m moving the good stuff that is left over here!

Leave a Reply

Your email address will not be published. Required fields are marked *