// CSE 143, Winter 2009, Marty Stepp // A Downloader object is able to read a given URL and download it to a file. // This class demonstrates opening input streams to read from URLs, opening an // output stream to write to a file, and method headers that throw exceptions. import java.io.*; import java.net.*; public class Downloader { private URL url; // Constructs a new downloader to read from the URL with the given text // representation, such as "http://www.google.com/". // Throws a MalformedURLException if this is not a valid URL. public Downloader(String urlString) throws MalformedURLException { url = new URL(urlString); } // Reads from this downloader's URL and writes its contents to the given file. // Throws an IOException if there is any error while reading/writing data. public void download(String targetFileName) throws IOException { InputStream in = url.openStream(); FileOutputStream out = new FileOutputStream(targetFileName); while (true) { int n = in.read(); if (n == -1) { // -1 means end-of-file break; } out.write(n); } in.close(); out.close(); } }