Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Chapter 33: Creating a Download Manager in Java 967


The Download Class


TheDownloadclass is the workhorse of the Download Manager. Its primary purpose is to
download a file and save that file’s contents to disk. Each time a new download is added
to the Download Manager, a newDownloadobject is instantiated to handle the download.
The Download Manager has the ability to download multiple files at once. To achieve
this, it’s necessary for each of the simultaneous downloads to run independently. It’s also
necessary for each individual download to manage its own state so that it can be reflected
in the GUI. This is accomplished with theDownloadclass.
The entire code forDownloadis shown here. Notice that it extendsObservableand
implementsRunnable. Each part is examined in detail in the sections that follow.

import java.io.*;
import java.net.*;
import java.util.*;

// This class downloads a file from a URL.
class Download extends Observable implements Runnable {
// Max size of download buffer.
private static final int MAX_BUFFER_SIZE = 1024;

// These are the status names.
public static final String STATUSES[] = {"Downloading",
"Paused", "Complete", "Cancelled", "Error"};

// These are the status codes.
public static final int DOWNLOADING = 0;
public static final int PAUSED = 1;
public static final int COMPLETE = 2;
public static final int CANCELLED = 3;
public static final int ERROR = 4;

FIGURE 33-1 The Download Manager GUI inter face
Free download pdf