我想在下面的代码中添加多个连接,以便能够更快地下载文件。有人能帮助我吗?提前谢谢。
public void run() {
RandomAccessFile file = null;
InputStream stream = null;
try {
// Open connection to URL.
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
// Specify what portion of file to download.
connection.setRequestProperty("Range",
"bytes=" + downloaded + "-");
// Connect to server.
connection.connect();
// Make sure response code is in the 200 range.
if (connection.getResponseCode() / 100 != 2) {
error();
}
// Check for valid content length.
int contentLength = connection.getContentLength();
if (contentLength < 1) {
error();
}
/* Set the size for this download if it
hasn't been already set. */
if (size == -1) {
size = contentLength;
stateChanged();
}
// Open file and seek to the end of it.
file = new RandomAccessFile("C:\\"+getFileName(url), "rw");
file.seek(downloaded);
stream = connection.getInputStream();
while (status == DOWNLOADING) {
/* Size buffer according to how much of the
file is left to download. */
byte buffer[];
if (size - downloaded > MAX_BUFFER_SIZE) {
buffer = new byte[MAX_BUFFER_SIZE];
} 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();
}
/* Change status to complete if this point was
reached because downloading has finished. */
if (status == DOWNLOADING) {
status = COMPLETE;
stateChanged();
}
} catch (Exception e) {
error();
} finally {
// Close file.
if (file != null) {
try {
file.close();
} catch (Exception e) {
}
}
// Close connection to server.
if (stream != null) {
try {
stream.close();
} catch (Exception e) {
}
}
}
}
答案 0 :(得分:1)
你可以使用线程。
将用于下载和更新RandomAccessFile的代码放在Thread / Runnable中并启动它的多个实例。
使用全局计数器(同步访问)来跟踪完成下载的线程数,并使主线程等到所有线程都在关闭文件之前增加计数器。
确保同步对RandomAccessFile的所有访问,以便线程A在写入文件的另一部分时不能调用seek(somePosition)
。
答案 1 :(得分:0)
确保描述您的想法。多线程的开销和它们之间的协调可能会使代码变慢。 不要这样做,除非你确定这是一个瓶颈,代码复杂性会增加,调试这是非常重要的。