gpt4 book ai didi

java - 如何使用多线程通过FTP下载文件?

转载 作者:行者123 更新时间:2023-11-29 06:05:38 26 4
gpt4 key购买 nike

我有以下任务:制作用于从 FTP 服务器(300 兆字节)下载 1,000 个文件的 Android 程序。现在我已经制作了一个程序来解析文件树并将其下载到 SDCard 中。但是会花很多时间(40分钟),而且效果不好,需要减少下载时间。正在使用代码下载文件:

BufferedOutputStream buffIn=new BufferedOutputStream(new FileOutputStream(f));
mClient.retrieveFile(ftpFile.getName(), buffIn);
buffIn.close();

但是我该如何使用多线程呢?我使用 apache-commons 库,FTPClient 类。我认为我不应该将下载代码复制到 Thread 中,这对我有帮助。请帮帮我,我怎样才能减少下载时间?

最佳答案

建立多个连接以从 FTP 服务器下载文件可能只有在该服务器限制每个连接的带宽时才有用,就像@fge 在评论中所表达的那样。

让我们看一些例子:

假设您有一个 8 mbps 的互联网连接,理论上最大下载速度为 1 兆字节/秒。

Scenario 1: You're downloading a 100 megabyte file from an FTP server that doesn't impose a download limit.

If you're downloading the file using one connection, you download it at 1 megabyte/sec, what takes you 100 seconds (1min 40sec).

By using two connections (assuming it is possible over FTP to download different pieces of one file at the same time) you download the file at 0.5 megabytes/sec for each connection, totaling 1 megabyte/sec, what also takes you 100 seconds (1min 40sec) to download the file.

So we conclude that, in this scenario, multiple connections do not help.


Scenario 2: You're downloading a 100 megabyte file from an FTP server that imposes a download limit of 0.5 megabytes/sec for each connection.

If you're downloading the file using one connection, you download it at 0.5 megabytes/sec (imposed by the server), what takes you 200 seconds (3min 20sec).

By using two connections (assuming it is possible over FTP to download different pieces of one file at the same time) you download the file at 0.5 megabytes/sec for each connection, totaling 1 megabyte/sec, taking you 100 seconds (1min 40sec) to download the file.

So we conclude that, in this scenario, multiple connections do actually help.


Scenario 3: You're downloading multiple files - let's say two files of 100 megabytes each - from an FTP server (download limit disregarded as we've already seen that when a limit is imposed, multiple connections can help).

If you're downloading both files at the same time using one connection per file (two connections), you download each of the files at 0.5 megabytes/sec, what takes you 200 seconds (3min 20sec) to download both files. In other words, you only get the two files after 200 seconds.

On the other hand, downloading the files one by one, having only one connection at a time, you download both files at 1 megabyte/sec, what also takes 200 seconds (3min 20sec), but you get the first file after only 100 seconds (1min 20sec), and the seconds one 100 seconds later.

So we conclude that, in this scenario, it depends on whether the files are useful by themselves, or only as a whole.

很抱歉无法直接解决您的问题,但我认为您应该首先考虑这种情况,并了解在您的情况下是否可以从多个连接中获得一些东西。

关于java - 如何使用多线程通过FTP下载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8629525/

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