我用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");
}
答案 0 :(得分:2)
我会使用二进制文件下载二进制文件,当我运行时我得到
SUM()
打印
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);
}
}
几乎是6 MB / s
如果忽略文件为二进制文件的事实,仅用于性能比较。
Took 0.541 seconds to read 3.146 MB of data
打印
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);
}
}
所以它可能会稍慢,或者只是随机变化。
相比之下,使用StringBuilder并一次读取一行可能会更慢,但不会显着
Took 0.548 seconds to read 3.146 MB of data