gpt4 book ai didi

java - 下载文件太慢了

转载 作者:行者123 更新时间:2023-11-30 02:48:30 26 4
gpt4 key购买 nike

我用 Opera 浏览器和 Java 代码尝试了相同的文件。

Opera 浏览器的速度接近 2 MB/s,但 Java 代码的速度不超过 400 KB/s。我的代码有什么问题吗?

我想我用 BufferedReader 阅读时做错了,但我不知道为什么会发生这种情况以及如何修复。

PS:我只是进行速度测试,而不是运行文件。我知道它是一个二进制文件,这对速度有什么影响吗?

            StringBuilder builder = new StringBuilder();
HttpURLConnection uri = (HttpURLConnection) new URL("http://speedtest.tele2.net/3MB.zip").openConnection();
uri.setRequestMethod("GET");
uri.setConnectTimeout(5000);
InputStream ent = uri.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(ent, "iso-8859-1"), 8);
while ((line = reader.readLine()) != null) {
builder.append(line + "\n");
}

最佳答案

我会使用二进制下载来下载二进制文件,当我运行这个时,我得到

public class DownloadMain {
public static void main(String[] args) throws IOException {
HttpURLConnection uri = (HttpURLConnection) new URL("http://speedtest.tele2.net/3MB.zip").openConnection();
uri.setRequestMethod("GET");
uri.setConnectTimeout(5000);
InputStream ent = uri.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bytes = new byte[8192];
long start = System.currentTimeMillis();
for (int len; (len = ent.read(bytes)) > 0; )
baos.write(bytes, 0, len);
long time = System.currentTimeMillis() - start;
System.out.printf("Took %.3f seconds to read %.3f MB of data%n",
time / 1e3, baos.toByteArray().length / 1e6);
}
}

打印

Took 0.541 seconds to read 3.146 MB of data

接近 6 MB/s

如果您忽略文件是二进制的事实,只是出于性能比较的目的。

public class DownloadMain {
public static void main(String[] args) throws IOException {
HttpURLConnection uri = (HttpURLConnection) new URL("http://speedtest.tele2.net/3MB.zip").openConnection();
uri.setRequestMethod("GET");
uri.setConnectTimeout(5000);
InputStream ent =uri.getInputStream();
Reader reader = new InputStreamReader(ent, StandardCharsets.ISO_8859_1);
StringWriter sw = new StringWriter();
char[] chars = new char[8192];
long start = System.currentTimeMillis();
for (int len; (len = reader.read(chars)) > 0; )
sw.write(chars, 0, len);
long time = System.currentTimeMillis() - start;
System.out.printf("Took %.3f seconds to read %.3f MB of data%n",
time / 1e3, sw.toString().length() / 1e6);
}
}

打印

Took 0.548 seconds to read 3.146 MB of data

所以它可能会稍微慢一些,或者只是随机变化。

相比之下,使用 StringBuilder 并一次读取一行可能会慢一些,但也不会太慢

Took 0.555 seconds to read 3.146 MB of data

关于java - 下载文件太慢了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39412398/

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