Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

974 Part IV: Applying Java


} else {
buffer = new byte[size - downloaded];
}

// Read from server into buffer.
int read = stream.read(buffer);
if (read == -1)
break;

// Write buffer to file.
file.write(buffer, 0, read);
downloaded += read;
stateChanged();
}

This loop is set up to run until the download’sstatusvariable changes from
DOWNLOADING. Inside the loop, abytebuffer array is created to hold the bytes that
will be downloaded. The buffer is sized according to how much of the download is left
to complete. If there is more left to download than theMAX_BUFFER_SIZE, theMAX_
BUFFER_SIZEis used to size the buffer. Otherwise, the buffer is sized exactly at the
number of bytes left to download. Once the buffer is sized appropriately, the downloading
takes place with astream.read( )call. This call reads bytes from the server and places them
into the buffer, returning the count of how many bytes were actually read. If the number of
bytes read equals –1, then downloading has completed and the loop is exited. Otherwise,
downloading is not finished and the bytes that have been read are written to disk with a call
tofile.write( ). Then thedownloadedvariable is updated, reflecting the number of bytes
downloaded thus far. Finally, inside the loop, thestateChanged( )method is invoked.
More on this later.
After the loop has exited, the following code checks to see why the loop was exited:

/* Change status to complete if this point was
reached because downloading has finished. */
if (status == DOWNLOADING) {
status = COMPLETE;
stateChanged();
}

If the download’s status is stillDOWNLOADING, this means that the loop exited because
downloading has been completed. Otherwise, the loop was exited because the download’s
status changed tosomething other thanDOWNLOADING.
Therun( )method wraps up with thecatchandfinallyblocks shown here:

} catch (Exception e) {
error();
} finally {
// Close file.
if (file != null) {
try {
file.close();
} catch (Exception e) {}
}
Free download pdf