Here is my DownloadFile.ja va.
In UI of the project, I want to provide user to select download speed as Fast, Medium, Slow.How can I do this.I have also threadPool structure in my project in DownloadManager .java and it only takes 10 downloads to the pool.Is download speed related with it?Or how can I increase or decrease the speed of downloads?Any idea would be appreciated.
Code:
public class DownloadFile extends Download implements Runnable, DownloadFileInterface {
private String name; //get name of the file
public DownloadFile(URL url, int id) {
super(url, id);
}
// Start downloading.
public void download() {
System.out.println("Downloading...");
InputStream stream = null;
File file = new File(getUrl());
RandomAccessFile rfile = null;
System.out.println("Download started: " + getId());
setName(file.getFileName());
try {
// Open connection to URL.
HttpURLConnection connection = (HttpURLConnection) getUrl()
.openConnection();
// Specify what portion of file to download.
connection.setRequestProperty("Range", "bytes=" + getDownloaded() + "-");
// Connect to server.
connection.connect();
int contentLength = connection.getContentLength();
System.out.println(contentLength);
/*
* Set the size for this download if it hasn't been already set.
*/
if (getSize() == -1) {
setSize(contentLength);
}
// Open file and seek to the end of it.
rfile = file.openRandomAccessFile();
rfile.seek(getDownloaded());
stream = connection.getInputStream();
while (getStatus() == DOWNLOADING) {
/*
* Size buffer according to how much of the file is left to
* download.
*/
byte buffer[];
if (getSize() - getDownloaded() > MAX_BUFFER_SIZE) {
buffer = new byte[MAX_BUFFER_SIZE];
// System.out.println("id: " + id + " downloaded byte: " +
// MAX_BUFFER_SIZE);
} else {
int remainingByte = getSize() - getDownloaded();
if (remainingByte <= 0) {
System.out.println(file.getFileName()
+ " has been downloaded");
break;
}
else {
buffer = new byte[remainingByte];
// System.out.println("id: " + id + " remaining byte: "
// + remainingByte);
}
}
// Read from server into buffer.
int read = stream.read(buffer);
// Write buffer to file.
rfile.write(buffer, 0, read);
setDownloaded(getDownloaded()+read);
}
/*
* Change status to complete if this point was reached because
* downloading has finished.
*/
if (getStatus() == DOWNLOADING) {
setStatus(COMPLETE);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("There is an Error!");
} finally {
// Close file.
if (rfile != null) {
try {
rfile.close();
} catch (Exception e) {
}
}
// Close connection to server.
if (stream != null) {
try {
stream.close();
} catch (Exception e) {
}
}
}
}
Comment