} 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's status variable changes from
DOWNLOADING. Inside the loop, a byte buffer 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 the MAX_BUFFER_SIZE, the MAX_
BUFFER_SIZE is 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 a stream.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
to file.write( ). Then the downloaded variable is updated, reflecting the number of bytes
downloaded thus far. Finally, inside the loop, the stateChanged( ) 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 still DOWNLOADING, this means that the loop exited because
downloading has been completed. Otherwise, the loop was exited because the download's
status changed to something other than DOWNLOADING.
The run( ) method wraps up with the catch and finally blocks shown here:
} catch (Exception e) {
error();
} finally {
// Close file.
if (file != null) {
try {
file.close();
} catch (Exception e) {}
}
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home