为什么使用Java下载文件速度这么慢
我编写了简单的 Java 下载器,但在速度方面存在一些问题。
一开始,速度还可以——就像我使用浏览器下载这个文件一样。但一段时间后,速度下降很多,每两秒改变一次 - 从 42kb/s 到 64kb/s,从 64kb/s 到 42kb/s。
我的代码:
InputStream is = null;
FileOutputStream os = null;
os = new FileOutputStream(...);
URL u = new URL(...);
URLConnection uc = u.openConnection();
is = uc.getInputStream();
final byte[] buf = new byte[1024];
for(int count = is.read(buf);count != -1;count = is.read(buf)) {
os.write(buf, 0, count);
}
我应该怎样做才能最大限度地提高下载速度?
更新
文件大小从 1 MB 到大约 100 MB 不等。 我将缓冲区增加到 65536,结果是一样的。
关于测量:我每 3 秒检查一次写入了多少字节,然后将其除以 3 和 1024 - 它给出了 kb/s
I wrote simple Java Downloader and I have some problems with speed.
At first, speed is OK - just like when I use my browser to download this file. But after a while speed decreases a lot and change every two seconds - from 42kb/s to 64kb/s and from 64kb/s to 42kb/s.
My code:
InputStream is = null;
FileOutputStream os = null;
os = new FileOutputStream(...);
URL u = new URL(...);
URLConnection uc = u.openConnection();
is = uc.getInputStream();
final byte[] buf = new byte[1024];
for(int count = is.read(buf);count != -1;count = is.read(buf)) {
os.write(buf, 0, count);
}
What should I do to maximalise speed of download?
UPDATE
Sizes of files are various from 1 to about 100MB.
I increased the buffer to 65536 to it is the same.
About measuring : I check every 3 second how many bytes was written, and then divide it by 3 and by 1024 - it gives me kb / s
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为了提高速度,在带宽和服务器容量的限制范围内,应用程序应该在多线程代码中使用多个连接(不止一个):每个线程创建自己的连接并查询文件的部分内容。
此类应用程序的一个示例是 IBM downloaddirector,它通常使用三个 HTTP 连接来检索大文件。大多数 FTP 客户端还能够使用多个连接来提高吞吐量。在Java中,可以使用Apache HttpClient来编写这样的多线程应用程序。
您没有详细说明您的 URL 中使用的协议。如果是 HTTP,则
HEAD
请求返回文件长度,并使用具有分块支持的GET
来查询文件部分。如果直接使用 HttpURLConnection 并设置 ChunkedStreamingMode 的值,即使使用单个连接,也可能获得更好的性能。
如果仍然不满意,请提供其他详细信息:
To increase speed, up to the limit of your bandwidth and server capacity, an application should use several connections (more than only one) with multi-threaded code: each thread creates its own connection and queries for parts of the file.
An example of such an application is IBM download director which often uses three HTTP connections to retrieve large files. Most FTP clients are also able to work with multiple connections to increase throughput. In Java, Apache HttpClient may be used to write such a multi-threaded application.
You have not detailed the protocol used in your URL. If HTTP, a
HEAD
request returns the file length andGET
with chunking support is used to query for file parts.Probably you can get better performance even with a single connection if you directly use HttpURLConnection and set value for ChunkedStreamingMode.
If still unsatisfied, please provide additional details: