Chapter 33: Creating a Download Manager in Java 971
// Notify observers that this download's status has changed.
private void stateChanged() {
setChanged();
notifyObservers();
}
}
The Download Variables
Downloadbegins by declaring severalstatic finalvariables that specify the various constants
used by the class. Next, four instance variables are declared. Theurlvariable holds the Internet
URL for the file being downloaded; thesizevariable holds the size of the download file in
bytes; thedownloadedvariable holds the number of bytes that have been downloaded thus
far; and thestatusvariable indicates the download’s current status.
The Download Constructor
Download’s constructor is passed a reference to the URL to download in the form of aURL
object, which is assigned to theurlinstance variable. It then sets the remaining instance
variables to their initial states and calls thedownload( )method. Notice thatsizeis set to –1
to indicate there is no size yet.
The download( ) Method
Thedownload( )method creates a newThreadobject, passing it a reference to the invoking
Downloadinstance. As mentioned before, it’s necessary for each download to run
independently. In order for theDownloadclass to act alone, it must execute in its own
thread. Java has excellent built-in support for threads and makes using them a snap. To use
threads, theDownloadclass simply implements theRunnableinterface by overriding the
run( )method. After thedownload( )method has instantiated a newThreadinstance, passing
its constructor theRunnable Downloadclass, it calls the thread’sstart( )method. Invoking
thestart( )method causes theRunnableinstance’s (theDownloadclass’)run( )method to
be executed.
The run( ) Method
When therun( )method executes, the actual downloading gets under way. Because of its
size and importance, we will examine it closely, line by line. Therun( )method begins with
these lines:
RandomAccessFile file = null;
InputStream stream = null;
try {
// Open connection to URL.
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();