Storing the contents of a URL to a file

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

URLFetcher.java:

import java.io.*;
import java.net.URL;

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 = is.read(buffer,0,1024)) != -1) {
      os.write(buffer, 0, numRead);
    }
    is.close();
    os.close();
  }
}

Using the URLFetcher:

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

 

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