When in the course of human events a developer needs to write a Java program to download the Declaration of Independence to a file and then display that file in a web browser, all he or she needs to code is something like this:

public class PageDownload implements Runnable {
    private static final String DECLARATION_URL = "https://www.archives.gov/founding-docs/declaration-transcript";

    public static void main(String[] args) throws Exception {
            // Create a File to receive the downloaded web page.
            File htmlDir = new File("html");
            htmlDir.mkdirs();
            File htmlFile = File.createTempFile("temp_", ".html", htmlDir);
            htmlFile.deleteOnExit();
            BufferedWriter wtr = new BufferedWriter(new FileWriter(htmlFile));

            // URL, URLConnection, and the latter's getInputStream are the basis
            // for reading a file on the Internet. In fact, URL has an openInputStream()
            // method which accomplishes the same thing.
            URL url = new URL(address);
            URLConnection conn = url.openConnection();
            InputStream in = conn.getInputStream();
            BufferedReader rdr = new BufferedReader(new InputStreamReader(in));

            // We're going to copy the file from the Internet to a
            // temporary file on disk, and then display it in our
            // web browser.
            StringBuilder html = new StringBuilder();
            char[] buffer = new char[2048];
            int length = 0;
            while ((length = rdr.read(buffer)) >= 0) {
                html.append(buffer, 0, length);
                wtr.write(buffer, 0, length);
            }
            System.out.println(html.length() + " bytes were read from " + address + ".");

            rdr.close();
            wtr.flush();
            wtr.close();

            // If a web browser is available, call the browse() method
            // of Desktop to display the HTML file we've written.
            if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
                Desktop.getDesktop().browse(htmlFile.toURI());
            } else {
                System.out.println("Browsing is not supported on your system.");
            }

        } catch (Throwable e) {
            this.exception = e;
        }

Wasn’t that easy? Now try creating a project in your workspace that contains the code above and try running it. Good luck!

What You Need to Know

  • Downloading a file–any file–from the Internet is as simple as opening a URL to it and getting an InputStream from either the URL object or it’s URLConnection.
  • The Desktop class provides access to some application features on your system.

We’ll be using this code in Lesson 26: Threads