gpt4 book ai didi

Java多连接下载文件

转载 作者:太空宇宙 更新时间:2023-11-04 08:54:17 24 4
gpt4 key购买 nike

我想在下面的代码中添加多个连接以便能够更快地下载文件。有人可以帮助我吗?提前致谢。

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) {
}
}
}
}

最佳答案

您可以使用线程。

将下载和更新 RandomAccessFile 的代码放入 Thread/Runnable 中,并启动它的多个实例。

使用全局计数器(同步访问)来跟踪有多少线程完成下载,并让主线程等待,直到所有线程都增加计数器后再关闭文件。

确保同步对 RandomAccessFile 的所有访问,以便线程 A 在线程 B 写入文件的另一部分时无法调用 seek(somePosition)

关于Java多连接下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2701272/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com